<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */


namespace app\api\controller\android\v12;


use app\api\model\Aliyunoss;
use app\api\model\Authority;
use app\api\model\Capital;
use app\api\model\Client;
use app\api\model\Common;
use app\api\model\House;
use app\api\model\PollingModel;
use app\api\model\schemeMaster;
use app\index\model\Pdf;
use Redis\RedisPackage;
use think\Controller;
use think\Exception;
use think\Request;
use  app\api\model\OrderModel;
use app\api\validate;
use Think\Db;
use  app\api\model\Approval;


class Order extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;


    public function _initialize()
    {
        $this->model    = new Authority();
        $this->pdf      = new Pdf();
        $this->us       = Authority::check(1);
        $this->newTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -5 minutes")));
        $this->endTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -10 minutes")));
        $this->overtime = strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s', strtotime('+1minute')))));
    }

    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need(OrderModel $orderModel, House $house)
    {

        $data           = $this->model->post(['channel_id', 'pro_id', 'province_id', 'city_id', 'county_id', 'addres', 'contacts', 'telephone', 'remarks', 'logo', 'lat', 'lng', 'channel_details', 'hardbound']);
        $Order_Validate = new validate\Order_Validate();
        if (!$Order_Validate->check($data)) {
            r_date($Order_Validate->getError(), 300);
        }
        if (!is_mobile($data['telephone'])) {
            r_date([], 300, '请输入正确的手机号');
        }

        try {
            $city_id=0;
            $province=0;
            $county=0;
            if ($data['province_id']) {
                $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
            }
            if ($data['county_id']) {
                $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
            }

            if ($data['channel_details'] == 102 || $data['channel_details'] == 100 || $data['channel_details'] == 96) {
                $time = time();
            } else {
                $time = '';
            }
            $content=0;
            if($city_id !=0){
                $content=$orderModel->UrbanAccess($city_id);
            }
            $house = $house->getHouse(['province' => $province, 'city' => $city_id, 'area' => $county, 'communityName' => $data['communityName'], 'address' => $data['addres'], 'latitude' => $data['lat'], 'longitude' => $data['lng']]);
            if($content==0){
                $order=db('order');
            }else{
				$order=Db::connect($content)->table('order');
            }
            $res   = $order->insertGetId(['channel_id' => $data['channel_id'],//渠道
                'channel_details' => $data['channel_details'],//渠道
                'order_no' => order_sn(),//订单号
                'pro_id' => $data['pro_id'],//一级问题
                'province_id' => $province,//省
                'city_id' => $city_id,//市
                'county_id' => $county,//区
                'addres' => $data['addres'],//地址
                'contacts' => $data['contacts'],//联系人
                'telephone' => $data['telephone'],//联系电话
                'remarks' => $data['remarks'],//备注
                'residential_quarters' => $data['communityName'],//备注
                'logo' => !empty($data['logo']) ? serialize(json_decode($data['logo'], true)) : '',//图片
                'street' => $data['street'],
                'building' => $data['building'],
                'unit' => $data['unit'],
                'room' => $data['room'],
                'state' => 0,//待指派
                'created_time' => time(),//创建时间
                'update_time' => time(),//创建时间
                'lat' => $data['lat'],//创建时间
                'lng' => $data['lng'],//创建时间
                'notcost_time' => $time,//创建时间
                'intention' => $this->us['user_id'],//创建时间
                'entry' => '店长录入-' . $this->us['username'],//创建时间
                'house_id' => $house,//创建时间
                'hardbound' => $data['hardbound'],//创建时间
                'entry_user_id' => $this->us['user_id'],//创建时间
                'entry_type' => 1,
                'hematopoiesis' => 1,
            ]);
//            if ($data['assignor'] == 0) {
//
//            }
            (new PollingModel())->Alls($res, 0, 0, time(), time());
//            else {
//                db('cc_scheme_label', \config('database.zong'))->insert(['order_id' => $res->order_id, 'pro_id' => $data['pro_id'], 'house_id' => $house, 'select' => 1]);
//
//                db('remind')->insertGetId([
//                    'admin_id' => $this->us['user_id'],
//                    'order_id' => $res->order_id,
//                    'time' => time(),
//                    'stater' => 1,
//                    'tai' => 1,
//                ]);
//                $content = "店长输入的订单";
//                db('message')->insertGetId([
//                    'type' => 6,
//                    'content' => $content,
//                    'order_id' => $res->order_id,
//                    'time' => time(),
//                    'already' => 1,
//                    'user_id' => $this->us['user_id'],
//                ]);
//            }

            sendOrder($res);
            r_date(null, 200);
        } catch (Exception $e) {
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * @throws Exception
     * 提醒个数
     */
    public function Unread()
    {

        $coun1 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 1, 'tai' => 1])->count();
        $coun2 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 2, 'tai' => 1])->count();
        //        $coun3 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 3, 'tai' => 1])->count();
        //        $coun4 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 4, 'tai' => 1])->count();
        //        $coun5 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 5, 'tai' => 1])->count();
        //        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();
        //        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();

        $couns = ['zhu' => [//                0=>$coun1,
            //                1=>$coun2,
            0 => 0, 1 => 0,],];

        r_date($couns, 200);

    }

    /**
     * 修改地址
     * cate_id 二级id
     */
    public function edit_di(OrderModel $orderModel, House $house)
    {
        $data = $this->model->post(['order_id', 'province_id', 'city_id', 'county_id', 'addres', 'lat', 'lng', 'communityName', 'street', 'building', 'unit', 'room']);
        $orderModel->startTrans();
        try {
            if ($data['province_id']) {
                $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"]])->value('city_id');
            }
            if ($data['county_id']) {
                $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"]])->value('county_id');
            }
            $house = $house->getHouse(['province' => $province, 'city' => $city_id, 'area' => $county, 'communityName' => $data['communityName'], 'address' => $data['addres'], 'latitude' => $data['lat'], 'longitude' => $data['lng']]);
            $orderModel::update(['province_id' => $province, 'city_id' => $city_id, 'county_id' => $county, 'addres' => $data['addres'], 'street' => $data['street'],
                'building' => $data['building'], 'unit' => $data['unit'], 'room' => $data['room'], 'house_id' => $house, 'residential_quarters' => $data['communityName']], ['order_id' => $data['order_id']]);

            db('cc_scheme_label', \config('database.zong'))->where(['order_id' => $data['order_id']])->update(['house_id' => $house]);
            db()->commit();
            json_decode(sendOrder($data['order_id']), true);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }


    }

    /**
     * 修改配送地址
     * cate_id 二级id
     */
    public function Distribution(OrderModel $orderModel)
    {
        $data           = $this->model->post();
        $agency_address = '';
        if (isset($data['agency_address'])) {
            $agency_address = $data['agency_address'];
            $res            = $orderModel::update(['agency_address' => $agency_address], ['order_id' => $data['order_id']]);
        } else {
            $agency_address = $data['goodsCategoryId'];
            $res            = $orderModel::update(['pro_id1' => $agency_address], ['order_id' => $data['order_id']]);
        }

        if ($res) {
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            r_date([], 200, '新增成功');
        }

        r_date([], 300, '新增失败');

    }

    /**
     * 获取渠道
     */
    public function get_my_qu()
    {
        $res = db('chanel')->field('id,title')->whereIn('id', [28, 7, 4, 30, 13, 27, 31,29])->where('type', 1)->select();
        foreach ($res as $k => $item) {
            $data = db('channel_details')->where('type', 1)->where('pid', $item['id'])->field('id,title')->select();
            if (empty($data)) {
                $res[$k]['data'] = [];
            } else {
                $res[$k]['data'] = $data;
            }

        }
        r_date($res);
    }

    /**
     * 获取问题
     */
    public function get_my_wen()
    {
        $res = db('goods_category')->field('goods_category.title,goods_category.id')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0, 'type' => 1])->select();
        r_date($res);
    }

    /**
     * 获取问题
     */
    public function getSecond()
    {
        $data = \request()->get();

        $res = db('goods_category')->field('goods_category.title,goods_category.id')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => $data['id'], 'type' => 1])->select();
        r_date($res);
    }

    /**
     * 智能报价
     */
    public function IntelligentQuotation()
    {
        $res = db('goods_category')->field('title,parent_id,id,type')->where(['pro_type' => 1, 'is_enable' => 1])->select();
        foreach ($res as $v) {
            if ($v['parent_id'] == 0 && $v['type'] == 2) {
                $op[] = $v;
            } else if ($v['type'] == 1) {
                $opp[] = $v;
            }
        }
        foreach ($op as $v) {
            $data = [];
            foreach ($opp as $item) {
                if ($v['id'] == $item['parent_id']) {
                    $data[] = $item;
                }
            }
            $da[] = ['title' => $v['title'], 'data' => $data,];
        }
        foreach ($da as $kef => $item) {
            $p = '';
            foreach ($item['data'] as $k => $it) {
                $p .= $it['id'] . ',';
            }
            $p     = substr($p, 0, -1);
            $res   = db('goods_category')->field('title,parent_id,id,type')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => ['in', $p]])->select();
            $daa[] = ['title' => $item['title'], 'data' => $res,];
        }
        r_date($daa);
    }

    /**
     * 获取比例
     */
    public function expense(Common  $common)
    {
        $data         = Request::instance()->post(['orderId']);
        $list = $common->coupon($data['orderId']);
        r_date(['num' => config('expense'), 'agentRatio' => config('purchasing_expense'),'coupon'=>count($list)], 200);
    }

    /**
     * 获取智能报价
     */
    public function smartOptions()
    {
        $data         = Request::instance()->post(['id']);
        $res          = db('goods_category')->field('mandatory,optional,id,kind')->where(['id' => ['in', $data['id']], 'pro_type' => 1, 'is_enable' => 1])->select();
        $mandatory    = '';
        $optional     = '';
        $Intelligence = '';
        foreach ($res as $i) {
            if (!empty($i['mandatory']) && $i['kind'] == 2) {
                $Intelligence .= $i['mandatory'] . ',';
            }
            if (!empty($i['mandatory']) && $i['kind'] == 1) {
                $mandatory .= $i['mandatory'] . ',';
            }
            if (!empty($i['optional']) && $i['kind'] == 1) {
                $optional .= $i['optional'] . ',';
            }
        }
        $pr = [];
        if (!empty($mandatory)) {
            $mandatory = substr($mandatory, 0, -1);
            $rdetailed = db('detailed')->where(['serial' => ['in', $mandatory], 'tao' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['detailed_id'];
                $pr[$k]['projectMoney'] = $l['artificial'];
                $pr[$k]['projectTitle'] = $l['detailed_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 1;
                $pr[$k]['type']         = 1;
                unset($rdetailed[$k]);
            }

        }

        if (!empty($Intelligence)) {
            $Intelligence = substr($Intelligence, 0, -1);
            $rdetailed    = db('detailed')->whereIn('serial', $Intelligence)->where('tao', 0)->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();

            foreach ($rdetailed as $k => $l) {
                $prr[$k]['projectId']    = $l['detailed_id'];
                $prr[$k]['projectMoney'] = $l['artificial'];
                $prr[$k]['projectTitle'] = $l['detailed_title'];
                $prr[$k]['title']        = $l['title'];
                $prr[$k]['number']       = $l['number'];
                $prr[$k]['tao']          = 1;
                $prr[$k]['type']         = 2;
                unset($rdetailed[$k]);
            }

            $pr = array_merge($pr, $prr);

        }

        $option = [];
        if (!empty($optional)) {
            $optional  = substr($optional, 0, -1);
            $rdetailed = db('detailed')->where(['serial' => ['in', $optional], 'tao' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k => $l) {
                $option[$k]['projectId']    = $l['detailed_id'];
                $option[$k]['projectMoney'] = $l['artificial'];
                $option[$k]['projectTitle'] = $l['detailed_title'];
                $option[$k]['title']        = $l['title'];
                $option[$k]['number']       = $l['number'];
                $option[$k]['tao']          = 1;
                $option[$k]['type']         = 1;
                unset($rdetailed[$k]);
            }
        }
        r_date(['mandatory' => $pr, 'nonEssentialElection' => $option,]);
    }

    /*
     * 获取城市
     */
    public function city(\app\api\model\Common $common)
    {
        $data = Request::instance()->post();
        $list = $common->obtainCity($data['cityName'] ?? '');
        r_date($list, 200);
    }

    /*
     * 获取城市
     */
    public function latelyCity(\app\api\model\Common $common)
    {

        $list = $common->obtainCity('', 2);

        r_date($list, 200);

    }

    /**
     * 获取标题
     */
    public function Material()
    {
        $res = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->select();
        $po  = array_merge(array_unique(array_column($res, 'type')));
        foreach ($po as $k => $v) {
            $data = [];
            foreach ($res as $value) {
                if ($v == $value['type']) {
                    $data['title']  = $value['class_table'];
                    $data['type']   = $v;
                    $data['data'][] = $value;
                    $data['count']  = count($data['data']);
                }
            }
            unset($data['data']);
            $r[] = $data;
        }

        $custom          = [];
        $cpurchase       = [];
        $custom_material = db('custom_material')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->field('id,company,stock_name,latest_cost')->select();


        $custom[0]['title'] = '自购入库材料';
        $custom[0]['type']  = 0;
        $custom[0]['count'] = count($custom_material);

        $cpurchase_usage = db('purchase_usage')->where(['store_id' => $this->us['store_id']])->where('status', 3)->where('number', 'neq', 0)->field('id,company,stock_name,latest_cost')->select();

        $cpurchase[0]['title'] = '采购入库材料';
        $cpurchase[0]['type']  = 99;
        $cpurchase[0]['count'] = count($cpurchase_usage);

        r_date(array_merge(array_merge($r, $custom), $cpurchase), 200);
    }

    /**
     * 获取列表
     */
    public function Material_list()
    {
        $data = Request::instance()->post(['type']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,latest_cost,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->select();
        } else {
            $custom = db('stock')->field('id,company,stock_name,latest_cost')->where('type', $data['type'])->select();
        }


        r_date($custom, 200);
    }

    //材料费用提交
    public function material_usage()
    {
        $data            = Request::instance()->post();
        $data['storeId'] = $this->us['store_id'];
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点');
        }
        $material_usage = json_decode($data['materialJson'], true);
        db()->startTrans();
        try {
            $p                  = 0;
            $material_usageList = [];
            foreach ($material_usage as $datum) {
                $op  = u8queryForStoreId($datum['Material_id'], $this->us['store_id']);
                $u8c = json_decode($op, true);
                if ($u8c['status'] == 'success') {
                    $number = $u8c['data'];
                    if (!is_array($number)) {
                        $number = json_decode($u8c['data'], true);
                    }

                    if ($number['datas'][0]['nnum'] - $datum['square_quantity'] < 0) {
                        throw new Exception('库存不足');
                    }
                    $pp = ['order_id' => $data['order_id'], 'material_name' => $datum['material_name'], 'Material_id' => 0, 'square_quantity' => $datum['square_quantity'], 'unit_price' => $datum['unit_price'], 'type' => $datum['type'], 'company' => $datum['company'], 'total_price' => round($datum['unit_price'] * $datum['square_quantity'], 2), 'user_id' => $this->us['user_id'], 'created_time' => time(), 'shopowner_id' => $this->us['user_id'], 'adopt' => time(), 'status' => 1, 'total_profit' => $datum['unit_price'] * $datum['square_quantity'], 'types' => 1, 'code' => $datum['Material_id'], 'invclasscode' => $datum['invclasscode']];

                    $material_usage = db('material_usage')->insertGetId($pp);
                    db('usage_record')->insertGetId(['id' => $material_usage, 'type' => $datum['type'], 'user_id' => $this->us['user_id'], 'number' => $datum['square_quantity'], 'created_time' => time(), 'order_id' => $data['order_id'], 'original_number' => $datum['square_quantity'], 'unified' => $datum['Material_id']]);
                    $material_usageList[] = [
                        'Material_id' => $datum['Material_id'],
                        'square_quantity' => $datum['square_quantity'],
                        'unit_price' => $datum['unit_price'],
                        'id' => $material_usage
                    ];
                    $p                    += $pp['total_price'];

                }
            }
            if (empty($material_usageList)) {
                throw new Exception('没有新的材料领用');
            }
            U8cForList($material_usageList, $data['order_id'], $this->us['store_id'], 1);

            if ((string)$p != $data['allMoney']) {
                throw new Exception('金额错误');
            }

            db()->commit();
            json_decode(sendOrder($data['order_id']), true);

            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            journal(['url' => '店长审核报错', 'data' => $e->getMessage()]);
            r_date(null, 300, $e->getMessage());
        }

    }

    /*
     * 费用报销
     */
    public function reimbursement(Approval $approval, OrderModel $orderModel, Common $common, MaterialScience $materialScience)
    {

        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['type'] == 2) {
                if (empty($data['receiptNumber'])) {
                    throw new Exception('收据编号不能为空');
                }

            }
            $my_string                   = explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id'] = $this->us['work_wechat_user_id'];
            $data['reserve']             = $this->us['reserve'];

            $io = '';
            if ($data['type'] == 4) {
                $s              = '';
                $capital_id     = json_decode($data['mainMaterialIds'], true);
                $mainMaterialId = array_column($capital_id, 'mainMaterialId');
                $money          = array_column($capital_id, 'money');
                $io             = implode(',', $mainMaterialId);
                $capital        = db('capital')->whereIn('capital_id', $io)->field('class_b,to_price,company')->select();
                foreach ($capital as $item) {
                    $s .= $item["class_b"] . '-' . $item["to_price"] . ',';
                }
                $s               = substr($s, 0, -1);
                $data['content'] = $data['remarks'] . ',' . $s;
                $data['money']   = array_sum($money);
            } else {
                $data['content'] = $data['remarks'];

            }
            if ($data['type'] != 4) {
                //签约金额
                $offer = $orderModel->TuiNewOffer($data['order_id']);
                if ($offer['amount'] != 0) {
                    if ($data['money'] > 100) {
                        $payment = $common::order_for_payment($data['order_id']);
                        if ($payment[0] / $offer['amount'] < 0.3) {
                            throw new Exception('项目收款小于30%,无法使用报销,请严格按照收款制度进行收款');
                        }

                    }

                } else {
                    throw new Exception('主合同金额为0,不能报销');
                }
            } else {
                //签约金额
                $offer = $orderModel->TotalProfit($data['order_id']);
                if ($offer['agencyMoney'] != 0) {
                    if ($data['money'] > 100) {
                        $payment = $common::order_for_payment($data['order_id']);
                        if ($payment[1] / $offer['agencyMoney'] < 0.5) {
                            throw new Exception('主材收款小于50%，无法使用请款，请严格按照收款进度进行收款');
                        }

                    }
                } else {
                    throw new Exception('代购合同金额为0,不能报销');
                }
            }
            $reimbursementList = db('reimbursement')->where(['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money']])->find();
            if (!empty($reimbursementList)) {
                throw new Exception('名称和金额重复');
            }
            $op = ['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money'], 'voucher' => !empty($data['img']) ? serialize($my_string) : '', 'created_time' => time(), 'user_id' => $this->us['user_id'], 'status' => 0, 'sp_no' => '', 'content' => $data['content'], 'classification' => $data['type'], 'submission_time' => time(), 'shopowner_id' => $this->us['user_id'], 'capital_id' => $io, 'payment_notes' => $data['payment_notes'], 'secondary_classification' => isset($data['secondary_classification']) ? $data['secondary_classification'] : 0];

            $reimbursementId = db('reimbursement')->insertGetId($op);
            if ($reimbursementId) {

                if ($data['type'] == 4) {

                    foreach ($capital_id as $value) {
                        if (empty($value['receiptNumber'])) {
                            throw new Exception('收据编号不能为空');
                        }
                        if (!empty($value['money'])) {
                            db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => $value['mainMaterialId'], 'bank_id' => $value['supplierId'], 'money' => $value['money'], 'receipt_number' => isset($value['receiptNumber']) ? $value['receiptNumber'] : '']);
                        }

                    }

                } else {
                    db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => '', 'bank_id' => $data['bankCardId'], 'money' => $data['money'], 'receipt_number' => isset($data['receiptNumber']) ? $data['receiptNumber'] : '']);
                }
                $title = array_search($data['type'], array_column($materialScience->list_reimbursement_type(2), 'type'));
                $title = $this->us['username'] . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
                db()->commit();
                json_decode(sendOrder($data['order_id']), true);
                $approval->Reimbursement($reimbursementId, $title, $this->us['username'], $data['type']);
                r_date(null, 200);
            }

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }

    }

    /*
     * 供应商添加
     */
    public function agencyAdd()
    {
        $data = Request::instance()->post();

        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
        }
        if (isset($data['supplierId']) && !empty($data['supplierId']) != 0) {
            $count = db('agency')->where(['agency_id' => $data['supplierId']])->value('collection_number');

            if ($count == $data['collectionNumber']) {
                r_date(null, 300, '请勿重复录入');
            }

            $res = db('agency')->where('agency_id', $data['supplierId'])->update(['agency_name' => $data['agencyName'], 'range' => $data['range'], 'province' => $province, 'city' => $city_id, 'area' => $county, 'business' => $data['business'], 'product_notes' => $data['productNotes'], 'belonging_to' => $data['belongingTo'], 'scope_business' => $data['scopeBusiness'], 'contacts' => $data['contacts'], 'telephone' => $data['telephone'], 'account_type' => $data['accountType'], 'collection_name' => $data['collectionName'], 'collection_number' => $data['collectionNumber'], 'bank' => $data['bank'], 'bank_of_deposit' => $data['bankOfDeposit']]);
        } else {
            $res = db('agency')->insertGetId(['agency_name' => $data['agencyName'], 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'], 'range' => $data['range'], 'province' => $province, 'city' => $city_id, 'area' => $county, 'business' => $data['business'], 'product_notes' => $data['productNotes'], 'belonging_to' => $data['belongingTo'], 'scope_business' => $data['scopeBusiness'], 'contacts' => $data['contacts'], 'telephone' => $data['telephone'], 'account_type' => $data['accountType'], 'collection_name' => $data['collectionName'], 'collection_number' => $data['collectionNumber'], 'bank' => $data['bank'], 'bank_of_deposit' => $data['bankOfDeposit'], 'state' => 1, 'creation_time' => time(), 'random_number' => date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 2)]);
        }

        if ($res === false) {
            r_date(null, 300);
        }
        r_date(['agency_id' => $res, 'agency_name' => $data['agencyName']], 200);
    }


    /*
     * 代购主材合作公司
     */
    public function PartnerCompany(Approval $approval)
    {
        $parem  = Request::instance()->post();
        $common = new \app\api\model\Common();
        $data   = db('agency')->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left');
        if (isset($parem['title']) && $parem['title'] != '') {
            $data->where(function ($query) use ($parem) {
                $query->whereOr('agency.agency_name', 'Like', "%{$parem['title']}%")->whereOr('agency.contacts', 'Like', "%{$parem['title']}%")->whereOr('agency.telephone', 'Like', "%{$parem['title']}%");
            });
        }
        $data->where('agency.state', '=', 1);
        $list = $data->field('agency.agency_id,agency.contacts,agency.telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->select();

        foreach ($list as $k => $item) {
            $reimbursement = db('reimbursement')->join('reimbursement_relation', 'reimbursement_relation.reimbursement_id=reimbursement.id', 'left')->where('reimbursement_relation.bank_id', $item['agency_id'])->where('reimbursement.classification', 4)->where('reimbursement.user_id', $this->us['user_id'])->where('reimbursement.type', 1)->order('reimbursement.id desc')->value('reimbursement_relation.bank_id');
            if ($item['agency_id'] == $reimbursement) {
                $list[$k]['recentUse'] = 1;
            } else {
                $list[$k]['recentUse'] = 0;
            }

            $list[$k]['business'] = is_numeric($item['business']) ? array_values($approval->filter_by_value($common->supply(), 'id', $item['business']))[0]['title'] : $item['business'];
            if ($item['user_id'] == 0) {
                $list[$k]['remarks'] = '公司添加';
            } else {
                $list[$k]['remarks'] = $item['store_name'] . '-店长';
            }
            unset($list[$k]['store_name'], $list[$k]['user_id']);
        }
        $recentUse = array_column($list, 'recentUse');
        $agency_id = array_column($list, 'agency_id');
        array_multisort($recentUse, SORT_DESC, $agency_id, SORT_DESC, $list);
        r_date($list, 200);
    }

    /*
     * 影藏添加供应商
     */
    public function ShadowStorage()
    {
        r_date(0, 200);
    }

    /*
     * 是否有支付信息
     */
    public function PaymentInformation()
    {
        $parem = Request::instance()->post();
        $data  = db('agency')->where('agency_id', $parem['id'])->value('collection_number');
        $state = 1;
        if (empty($data)) {
            $state = 0;
        }
        r_date($state, 200);
    }

    /*
     * 合作和公司类型
     */
    public function TypeOfCooperation()
    {
        $common = new \app\api\model\Common();
        $data   = $common->supply();
        r_date($data, 200);
    }

    /*
     * 合作和公司类型
     */
    public function SupplierType()
    {
        $common = new \app\api\model\Common();
        $data   = $common->SupplierType();
        r_date($data, 200);
    }

    /*
     * 代购主材合作公司
     */
    public function PartnerCompany_add()
    {
        $data = Request::instance()->post();
        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
        }
        $res = db('agency')->insertGetId(['agency_name' => $data['agency_name'], 'province' => $province, 'city' => $city_id, 'area' => $county, 'business' => $data['business'], 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'],]);
        if ($res) {
            r_date([], 200);
        }
        r_date([], 300);
    }

    /*
     * 代购主材列表
     */
    public function PartnerCompany_capital(Approval $approval)
    {

        $data    = Request::instance()->post();
        $common  = new \app\api\model\Common();
        $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance')->select();
        foreach ($capital as $k => $v) {
            if ($v['fen'] == 1) {
                $product_chan = db('detailed')->where('detailed_id', $v['projectId'])->value('agency_id');
                $agency       = db('agency')->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left')->field('agency.agency_id,agency.contacts,agency.telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->whereIn('agency.agency_id', $product_chan)->where('agency.state', 1)->select();
                if ($agency) {
                    foreach ($agency as $o => $item) {
                        $agency[$o]['business'] = is_numeric($item['business']) ? array_values($approval->filter_by_value($common->supply(), 'id', $item['business']))[0]['title'] : $item['business'];
                    }
                    $capital[$k]['data'] = $agency;
                } else {
                    $capital[$k]['data'] = [];
                }

            } elseif ($v['fen'] == 2) {
                $product_chan = db('information')->where('id', $v['projectId'])->value('agency_id');
                $agency       = db('agency')->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left')->field('agency.agency_id,agency.contacts,agency.telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->whereIn('agency.agency_id', $product_chan)->where('agency.state', 1)->select();
                if ($agency) {
                    foreach ($agency as $j => $value) {
                        $agency[$j]['business'] = is_numeric($value['business']) ? array_values($approval->filter_by_value($common->supply(), 'id', $value['business']))[0]['title'] : $value['business'];
                    }
                    $capital[$k]['data'] = $agency;
                } else {
                    $capital[$k]['data'] = [];
                }
            } else {
                $capital[$k]['data'] = [];
            }
        }

        r_date($capital, 200);

    }

    /*
     * 自定义删除
     */
    public function custom_material_delect()
    {
        $data = Request::instance()->post();

        db('custom_material')->where('id', $data['id'])->update(['status' => 1]);

        r_date(null, 200);

    }

    /**
     * 获取材料
     */
    public function Material_translate()
    {
        $data = $this->model->post();
        $res  = db('stock')->field('id,company,stock_name,latest_cost,type');
        if (isset($data['title']) && $data['title'] != '') {
            $res->where(['stock_name' => ['like', "%{$data['title']}%"]]);
        }
        $res = $res->select();
        r_date($res, 200);
    }

    /**
     * 获取项目一级标题
     */
    public function get_my_ge()
    {
        $data = Request::instance()->post(['page' => 1, 'limit' => 10]);
        $res  = db('product_chan')->where(['parents_id' => 0, 'pro_types' => 1])->field('product_title,product_id')->select();
        foreach ($res as $k => $v) {
            $res[$k]['count'] = db('product_chan')->where(['parents_id' => $v['product_id'], 'pro_types' => 1])->count();
        }
        $re['tao']      = 0;
        $re['detailed'] = $res;
        $rdetailed      = db('detailed')->where(['detaileds_id' => 0, 'display' => 1, 'is_compose' => 0])->field('detailed_id,detailed_title')->page($data['page'], $data['limit'])->select();
        foreach ($rdetailed as $k => $v) {
            $rdetailed[$k]['count'] = db('detailed')->where(['detaileds_id' => $v['detailed_id']])->count();
        }
        $r['tao']      = 1;
        $r['detailed'] = $rdetailed;
        $data          = [0 => $re, 1 => $r,];
        r_date($data);
    }

    /**
     * 获取项目二级标题
     */
    public function get_my_er()
    {
        $data = Request::instance()->post(['type', 'detailed', 'page', 'limit']);
        $pr   = [];
        if ($data['type'] == 0) {

            $rdetailed = db('product_chan')->where(['parents_id' => $data['detailed'], 'pro_types' => 1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_id,product_title,parents_id,un.title,prices')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['product_id'];
                $pr[$k]['projectMoney'] = $l['prices'];
                $pr[$k]['projectTitle'] = $l['product_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 0;
                $pr[$k]['agency']       = 0;
                unset($rdetailed[$k]);
            }
        } elseif ($data['type'] == 1) {
            $detailed = db('detailed')->where(['detaileds_id' => $data['detailed'], 'tao' => 0, 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,agency')->page($data['page'], $data['limit'])->select();
            foreach ($detailed as $k => $l) {
                $pr[$k]['projectId']    = $l['detailed_id'];
                $pr[$k]['projectMoney'] = $l['artificial'];
                $pr[$k]['projectTitle'] = $l['detailed_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 1;
                $pr[$k]['agency']       = $l['agency'];
            }
        }
        r_date($pr);
    }

    /**
     * 获取项目二级标题
     */
    public function mandatory()
    {
        $data      = Request::instance()->post(['projectId']);
        $prr       = [];
        $rdetailed = db('detailed')->field('serial')->where(['detailed_id' => $data['projectId']])->find();
        if (!empty($rdetailed)) {
            $detailed_list = db('detailed_list')->field('relation')->where(['serial_id' => ['in', $rdetailed['serial']]])->find();
            if (!empty($detailed_list)) {
                $rdetailed = db('detailed')->where(['serial' => ['in', $detailed_list['relation']], 'tao' => 0, 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.detailed_id,detailed.detailed_title,detailed.detaileds_id,un.title,detailed.artificial,detailed.agency')->select();
                foreach ($rdetailed as $k => $l) {
                    $prr[$k]['projectId']    = $l['detailed_id'];
                    $prr[$k]['projectMoney'] = $l['artificial'];
                    $prr[$k]['projectTitle'] = $l['detailed_title'];
                    $prr[$k]['title']        = $l['title'];
                    $prr[$k]['tao']          = 1;
                    $prr[$k]['agency']       = $l['agency'];
                }
            }
        }
        r_date($prr);
    }

    /**
     * 基建赠送项目
     */
    public function get_zeng()
    {

        $res = db('product_chan')->where(['parents_id' => ['neq', 0], 'pro_types' => 1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_title,parents_id,un.title,prices')->order('product_id desc')->select();
        foreach ($res as $k => $l) {

            $pr[$k]['projectMoney'] = $l['prices'];
            $pr[$k]['projectTitle'] = $l['product_title'];
            $pr[$k]['title']        = $l['title'];
            $pr[$k]['tao']          = 0;
            $pr[$k]['agency']       = 0;
            unset($res[$k]);
        }
        $rdetailed = db('detailed')->where(['detaileds_id' => ['neq', 0], 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_title,detaileds_id,un.title,artificial,agency')->order('detailed_id desc')->select();
        foreach ($rdetailed as $k => $l) {
            $pr1[$k]['projectMoney'] = $l['artificial'];
            $pr1[$k]['projectTitle'] = $l['detailed_title'];
            $pr1[$k]['title']        = $l['title'];
            $pr1[$k]['tao']          = 1;
            $pr1[$k]['agency']       = $l['agency'];
            unset($rdetailed[$k]);
        }

        $data = array_merge($pr1, $pr);
        r_date($data);
    }

    /**
     * 基建搜索
     */
    public function despair()
    {
        $data = $this->model->post(['con']);
        $list = db('detailed')->field('detailed.detailed_title,detailed.detailed_id,detailed.artificial,un.title,detailed.tao,detailed.agency')->where(['detaileds_id' => ['neq', 0], 'detailed_title|serial' => ['like', "%{$data['con']}%"], 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->order('detailed_id desc')->select();
        $pr   = [];
        foreach ($list as $k => $l) {

            $pr[$k]['tao']          = 1;
            $pr[$k]['projectId']    = $l['detailed_id'];
            $pr[$k]['projectMoney'] = $l['artificial'];
            $pr[$k]['projectTitle'] = $l['detailed_title'];
            $pr[$k]['title']        = $l['title'];
            $pr[$k]['tao2']         = $l['tao'];
            $pr[$k]['agency']       = $l['agency'];

            unset($list[$k]);
        }
        r_date($pr);
    }

    /**
     * 基检搜索
     */
    public function set_jian()
    {

        $data = $this->model->post(['tao', 'detailed', 'sou1']);
        $s    = substr($data['detailed'], 0, -1);  //利用字符串截取函数消除最后一个逗号
        if ($data['tao'] == 0) {
            $product = db('product_chan')->where('product_id', 'in', $s)->field('parents_id,product_id,product_title')->select();
            foreach ($product as $o) {
                $product_chan = db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id' => $o['product_id'], 'parents_id' => $o['parents_id']])->field('product_title,prices,u.title,product_title,product_id')->select();
                foreach ($product_chan as $k => $l) {
                    $pr[$k]['projectId']    = $l['product_id'];
                    $pr[$k]['projectMoney'] = $l['prices'];
                    $pr[$k]['projectTitle'] = $l['product_title'];
                    $pr[$k]['title']        = $l['title'];
                    $pr[$k]['tao']          = 0;
                    $pr[$k]['agency']       = 0;
                    unset($product_chan[$k]);
                }
                $s   = ['big_title' => db('product_chan')->where(['product_id' => $o['parents_id']])->value('product_title'), 'data' => $pr, 'tao' => 0,];
                $p[] = $s;

            }
            r_date($p, 200);

        } elseif ($data['tao'] == 1) {
            if (!empty($data['detailed'])) {
                $product = db('detailed')->where(['detailed_id' => ['in', $s]])->field('detaileds_id,detailed_id')->select();
                foreach ($product as $o) {
                    $product_chan = db('detailed')->join('unit u', 'detailed.un_id=u.id', 'left')->where(['detailed_id' => $o['detailed_id'], 'detaileds_id' => $o['detaileds_id'], 'is_compose' => 0])->field('detailed.detailed_id,detailed.detailed_title,detailed.agency,artificial,u.title')->select();
                    foreach ($product_chan as $k => $l) {
                        $pr[$k]['projectId']    = $l['detailed_id'];
                        $pr[$k]['projectMoney'] = $l['artificial'];
                        $pr[$k]['projectTitle'] = $l['detailed_title'];
                        $pr[$k]['title']        = $l['title'];
                        $pr[$k]['tao']          = 1;
                        $pr[$k]['agency']       = $l['agency'];
                        unset($product_chan[$k]);
                    }
                    $s   = ['big_title' => db('detailed')->where(['detailed_id' => $o['detaileds_id']])->value('detailed_title'), 'data' => $pr, 'tao' => 1,];
                    $p[] = $s;
                }

            }
            if (!empty($data['sou1'])) {
                $s = substr($data['sou1'], 0, -1);  //利用字符串截取函数消除最后一个逗号
                $m = explode(",", $s);

                foreach ($m as $h) {
                    $pro  = db('product_chan')->where(['product_title' => $h])->field('parents_id,product_id')->find();
                    $pk[] = $pro;
                }
                foreach ($pk as $o) {
                    $produ = db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id' => $o['product_id'], 'parents_id' => $o['parents_id']])->select();
                    foreach ($produ as $k => $l) {
                        $kl[$k]['projectId']    = $l['product_id'];
                        $kl[$k]['projectMoney'] = $l['prices'];
                        $kl[$k]['projectTitle'] = $l['product_title'];
                        $kl[$k]['title']        = $l['title'];
                        $kl[$k]['tao']          = 0;
                        $pr[$k]['agency']       = 0;
                        unset($produ[$k]);
                    }
                    $s    = ['big_title' => db('product_chan')->where(['product_id' => $o['parents_id']])->value('product_title'), 'tao' => 0, 'data' => $kl,];
                    $p1[] = $s;
                }
            }
            if (!empty($data['sou1']) && !empty($data['detailed'])) {
                r_date(array_merge($p, $p1), 200);
            } elseif (!empty($data['detailed'])) {
                r_date($p, 200);
            } elseif (!empty($data['sou1'])) {
                r_date($p1, 200);
            }
        } elseif ($data['tao'] == 2) {
            $object = db('information')->where(['id' => ['in', $s], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
            foreach ($object as $o) {
                $product_chan = db('information')->where(['id' => $o['id'], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,agency')->select();
                foreach ($product_chan as $k => $l) {
                    $pr[$k]['projectId']    = $l['id'];
                    $pr[$k]['projectMoney'] = $l['un_Price'];
                    $pr[$k]['projectTitle'] = $l['class_b'];
                    $pr[$k]['title']        = $l['company'];
                    $pr[$k]['tao']          = 2;
                    $pr[$k]['agency']       = $l['agency'];
                    unset($product_chan[$k]);
                }
                $s   = ['big_title' => $l['class_a'], 'data' => $pr, 'tao' => 2,];
                $p[] = $s;
            }
            r_date($p, 200);
        }

    }


    /**
     * 基检编辑
     */
    public function updaty()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['fen'] == 0) {
                $product_chan = db('product_chan')->where('product_id', $data['projectId'])->find();
                $title        = db('unit')->where('id', $product_chan['units_id'])->value('title');
                $user         = ['company' => !empty($title) ? $title : '',//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $product_chan['prices'],//单价
                    'rule' => $product_chan['price_rules'],//规则
                    'zhi' => $data['zhi'],//规则
                    'to_price' => $product_chan['prices'] * $data['square'],//总价
                    'class_b' => $product_chan['product_title'],//三
                    'projectId' => $data['projectId'],//三
                    'fen' => 0,//状态
                    'class_a' => db('product_chan')->where(['product_id' => $product_chan['parents_id']])->value('product_title'),//三
                    'gold_suite' => 1,//三
                    'agency' => 0,//三

                ];
            } elseif ($data['fen'] == 1) {
                $detailed = db('detailed')->where('detailed_id', $data['projectId'])->find();
                $title    = db('unit')->where('id', $detailed['un_id'])->value('title');
                $user     = ['company' => !empty($title) ? $title : '',//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $detailed['artificial'],//单价
                    'rule' => $detailed['rmakes'],//规则
                    'zhi' => $data['zhi'],//规则
                    'to_price' => $detailed['artificial'] * $data['square'],//总价
                    'class_b' => $detailed['detailed_title'],//三
                    'projectId' => $data['projectId'],//三
                    'fen' => 1,//状态
                    'class_a' => db('detailed')->where(['detailed_id' => $detailed['detaileds_id']])->value('detailed_title'),//三
                    'gold_suite' => 1,//三
                    'agency' => $detailed['agency'],//三
                ];

            } elseif ($data['fen'] == 2) {
                $user = ['company' => $data['company'],//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $data['prices'],//单价
                    'to_price' => $data['square'] * $data['prices'],//总价
                    'zhi' => $data['zhi'],//规则
                    'fen' => 2,//状态
                    'projectId' => $data['projectId'],//三
                    'class_b' => $data['class_b'],//三
                    'class_a' => $data['class_a'],//三
                    'gold_suite' => 1,//三
                    'agency' => $data['agency'],//三

                ];
            }
            $res1 = db('capital')->where(['capital_id' => $data['capital_id']])->field('ordesr_id,to_price,agency')->find();
            $cap  = db('order')->where(['order_id' => $res1['ordesr_id']])->field('ification,planned,appointment,state')->find();
            if ($cap['state'] > 3) {
                throw  new  Exception('该项目无法编辑');
            }
            $thro = db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->field('through_id')->find();
            if ($thro) {
                $ca = db('envelopes')->where(['through_id' => $thro['through_id']])->field('give_money,purchasing_discount')->find();
            } else {
                $ca = db('envelopes')->where(['ordesr_id' => $res1['ordesr_id'], 'through_id' => 0])->field('give_money,purchasing_discount')->find();
            }
            $p3 = db('capital')->where(['capital_id' => $data['capital_id']])->update($user);
            if ($ca['purchasing_discount'] != 0) {
                $caps = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');

                if (($user['agency'] && $user['agency'] == 1) == ($res1['agency'] && $res1['agency'] == 1)) {
//                    if (($caps + $user['to_price'] * config('purchasing_discount')) < $ca['purchasing_discount']) {
//                        throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                    }
                } else {
                    if ((($caps - $user['to_price']) * config('purchasing_discount')) < $ca['purchasing_discount']) {
                        throw  new  Exception('代购项目不能为空');
                    }
                }
            }


            if ($ca['give_money'] != 0) {
                $to_price = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 0])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');

                if (($user['agency'] && $user['agency'] == 0) == ($res1['agency'] && $res1['agency'] == 0)) {
//                    if ((($to_price + $user['to_price']) * config('give_money')) < $ca['give_money']) {
//                        throw  new  Exception('优惠金额不能大于订单总价的10%');
//                    }
                } else {
                    if ((($to_price - $user['to_price']) * config('give_money')) < $ca['give_money']) {
                        throw  new  Exception('主材项目不能为空');
                    }
                }
            }


            if ($data['yc'] == 1) {
                $res2 = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->sum('to_price');
                db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->update(['amount' => $res2]);
            }


            if ($p3) {
                db()->commit();
                $this->pdf->put($res1['ordesr_id'], 1, $cap);
                json_decode(sendOrder($res1['ordesr_id']), true);

                $capitals = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();//代购主材;
                if ($capitals > 0) {
                    db('order')->where(['order_id' => $res1['ordesr_id']])->update(['order_agency' => 1]);
                } else {
                    db('order')->where(['order_id' => $res1['ordesr_id']])->update(['order_agency' => 0]);
                }
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * /**
     * 基检增项
     */
    public function amplification()
    {

        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment,tui_role,tui_jian,pro_id,state')->find();
            if ($cap['state'] > 3) {
                $Increment = 1;
                $signed    = 0;
            } else {
                $Increment = 0;
                $signed    = 1;
            }
            if ($data['yc'] == 1) {
                $programme = 3;
                $deal      = 1;
            } else {
                $programme = 1;
                $deal      = 0;
            }
            $envelopes_id = db('capital')->where(['envelopes_id' => $data['envelopes_id']])->find();
            $give_a       = '';//三
            $give_b       = '';//三
            $wen_a        = '';//一级分类
            $wen_b        = '';//二
            $wen_c        = '';//二

            if ($data['company']) {
                $op = json_decode($data['company']);
                $op = $this->object2array($op);
                foreach ($op as $ke => $v) {
                    if ($v['types'] == 0) {
                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users        = ['wen_a' => $wen_a, 'wen_b' => $wen_b, 'wen_c' => $wen_c, 'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['prices'],//单价
                            'rule' => $product_chan['price_rules'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 0,//状态
                            'to_price' => $product_chan['prices'] * $v['fang'],//总价
                            'crtime' => time(), 'ordesr_id' => $data['order_id'], 'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'enable' => $envelopes_id['enable'],//三
                            'programme' => $programme,//三
                            'signed' => $signed,//三
                            'give_a' => $give_a,//赠送项目
                            'give_b' => $give_b, 'projectId' => $v['product_id'],//三
                            'increment' => $Increment,//三
                            'agency' => $v['agency'],//三
                            'deal' => $deal,//三
                            'envelopes_id' => $envelopes_id['envelopes_id'],];

                    } elseif ($v['types'] == 1) {
                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users        = ['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['artificial'],//单价
                            'rule' => $product_chan['rmakes'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 1,//状态
                            'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                            'crtime' => time(), 'ordesr_id' => $data['order_id'], 'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '', 'enable' => $envelopes_id['enable'],//三
                            'programme' => $programme,//三
                            'give_a' => $give_a,//赠送项目
                            'signed' => $signed,//三
                            'give_b' => $give_b, 'projectId' => $v['product_id'],//三
                            'increment' => $Increment,//三
                            'agency' => $v['agency'],//三
                            'deal' => $deal,//三
                            'envelopes_id' => $envelopes_id['envelopes_id'],];

                    } elseif ($v['types'] == 2) {
                        $users = ['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'ordesr_id' => $data['order_id'], 'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'signed' => $signed,//三
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'crtime' => time(), 'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '', 'enable' => $envelopes_id['enable'],//三
                            'programme' => $programme,//三
                            'give_a' => $give_a,//赠送项目
                            'give_b' => $give_b, 'projectId' => $v['product_id'],//三
                            'increment' => $Increment, 'agency' => $v['agency'],//三
                            'deal' => $deal,//三
                            'envelopes_id' => $envelopes_id['envelopes_id'],];

                    }

                    db('capital')->insertGetId($users);
                    if ($cap['state'] > 3) {
                        $cli = new Client();
                        if ($v['agency'] == 1) {
                            $list = json_encode(["order_id" => $data['order_id'], "type" => 2, 'money' => $v['fang'] * $v['prices']]);
                            $cli->index($list, $cli::order_queue, $cli::order_routingkey);

                        } else {
                            $list = json_encode(["order_id" => $data['order_id'], "type" => 1, 'money' => $v['fang'] * $v['prices']]);
                            $cli->index($list, $cli::order_queue, $cli::order_routingkey);
                        }
                    }

                }
            }


            //            if ($cap['state'] > 3) {
            //
            //                if ($cap['tui_role'] == 2 && !empty($cap['tui_jian'])) {
            //                    $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$cap['tui_jian']])->find();
            //                    $deal            =0;
            //                    $group_proportion=0;
            //                    $money           =0;
            //                    if ($personal['num'] != 0) {
            //                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>$personal['num']])->find();
            //                    } else{
            //                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>0])->find();
            //                    }
            //
            //                    if ($ti) {
            //                        if ($personal['group'] == 0 && $personal['num'] != 0) {
            //                            $money           +=$to_price * $ti['bi'];
            //                            $deal            +=$to_price * $ti['bi'];
            //                            $group_proportion+=$to_price * $ti['group_proportion'];
            //                        } else{
            //                            $money+=$to_price * $ti['personal'];
            //                            $deal +=$to_price * $ti['personal'];
            //                        }
            //                        db('income')->insertGetId([
            //                            'personal_id'     =>$cap['tui_jian'],
            //                            'group_proportion'=>$group_proportion,
            //                            'deal'            =>$deal,
            //                            'profit'          =>$money,
            //                            'uptime'          =>time(),
            //                            'order_id'        =>$data['order_id'],
            //                            'mode'            =>'增加项目',
            //                        ]);
            //                    }
            //
            //                }
            //            }

            $this->pdf->put($data['order_id'], 1, $cap);
            $through = '';
            $WeChat  = 0;
            $s       = '';
            $res1    = db('capital')->where(['envelopes_id' => $envelopes_id['envelopes_id'], 'enable' => 1, 'types' => 1])->field('capital_id,to_price')->select();
            foreach ($res1 as $item) {
                $WeChat += $item['to_price'];
                $s      .= $item["capital_id"] . ',';
            }
            $s = substr($s, 0, -1);
            if ($data['yc'] == 1) {
                db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->update(['amount' => $WeChat, 'capital_id' => $s]);
                $through = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->value('through_id');
            }
            if ($envelopes_id['envelopes_id']) {
                $allow = db('allow')->where('envelopes_id', $envelopes_id['envelopes_id'])->find();
                if ($allow) {
                    db('allow')->where('id', $allow['id'])->update(['capital_id' => $s]);
                }
            }
            if (!empty($data['Warranty'])) {
                $Warranty = json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id' => $data['order_id'], 'warranty_id' => $value['warranty_id'], 'years' => $value['years'], 'creation_time' => time(), 'type' => 1, 'through_id' => $through, 'envelopes_id' => $envelopes_id]);
                }
            }

            db()->commit();
            json_decode(sendOrder($data['order_id']), true);
            $capitals = db('capital')->where(['envelopes_id' => $envelopes_id['envelopes_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();//代购主材;
            if ($capitals > 0) {
                db('order')->where(['order_id' => $data['order_id']])->update(['order_agency' => 1]);
            }
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /**
     * 基检删除
     */
    public function del(Approval $approval)
    {
        $data = Request::instance()->post();
        if (empty($data['capital_id']) && $data['capital_id'] != 0) {
            r_date([], 300, '参数错误');
        }
        db()->startTrans();
        try {

            $res1 = db('capital')->where(['capital_id' => $data['capital_id']])->field('ordesr_id,agency,to_price,signed,envelopes_id,class_b')->find();

            $cap = db('order')->where(['order_id' => $res1['ordesr_id']])->field('ification,planned,appointment,tui_role,tui_jian,pro_id,state')->find();
            if ($cap['state'] > 3 && !isset($data['quantity'])) {

                $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $res1['ordesr_id'])->whereNull('deleted_at')->sum('personal_price');

                $orderCapital = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $res1['ordesr_id'])->where('status', 1)->sum('money');
                if ($personal_price < $orderCapital) {
                    r_date([], 300, '不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
                }
                db('capital')->where(['capital_id' => $data['capital_id']])->update(['approve' => 3, 'reason_for_deduction' => $data['reasonForDeduction']]);
                $reimbursement = db('reimbursement_relation')->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id')->where(['reimbursement_relation.capital_id' => $data['capital_id']])->field('reimbursement.status,reimbursement.order_id')->find();
                if (!empty($reimbursement)) {
                    if ($reimbursement['status'] == 1 || $reimbursement['status'] == 0) {
                        throw  new  Exception('该代购主材已提交审批不能删除');
                    }
                }

                $work_time = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNull('deleted_at')->where('capital_id', $data['capital_id'])->value('work_time');
                if ($work_time != 0) {
                    throw  new  Exception('师傅工时不为0无法删除');
                }


//                Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $data['capital_id'])->update(['deleted_at' => time()]);
//                $cli = new Client();
//                if ($res1['agency'] == 1) {
//                    $list = json_encode(["order_id" => $res1['ordesr_id'], "type" => 2, 'money' => '-' . $res1['to_price']]);
//                    $cli->index($list, $cli::order_queue, $cli::order_routingkey);
//
//                } else {
//                    $list = json_encode(["order_id" => $res1['ordesr_id'], "type" => 1, 'money' => '-' . $res1['to_price']]);
//                    $cli->index($list, $cli::order_queue, $cli::order_routingkey);
//                }
                //                if ($cap['tui_role'] == 2 && !empty($cap['tui_jian'])) {
                //                    $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$cap['tui_jian']])->find();
                //                    $deal            =0;
                //                    $group_proportion=0;
                //                    $money           =0;
                //                    if ($personal['num'] != 0) {
                //                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>$personal['num']])->find();
                //                    } else{
                //                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>0])->find();
                //                    }
                //                    if ($ti) {
                //                        $toPrice=db('capital')->where('capital_id', $data['capital_id'])->sum('to_price');
                //                        if ($personal['group'] == 0 && $personal['num'] != 0) {
                //                            $money           +=$toPrice * $ti['bi'];
                //                            $deal            +=$toPrice * $ti['bi'];
                //                            $group_proportion+=$toPrice * $ti['group_proportion'];
                //                        } else{
                //                            $money+=$toPrice * $ti['personal'];
                //                            $deal +=$toPrice * $ti['personal'];
                //                        }
                //                        db('income')->insertGetId([
                //                            'personal_id'     =>$cap['tui_jian'],
                //                            'group_proportion'=>'-' . $group_proportion,
                //                            'deal'            =>'-' . $deal,
                //                            'profit'          =>'-' . $money,
                //                            'uptime'          =>time(),
                //                            'order_id'        =>$res1['ordesr_id'],
                //                            'mode'            =>'删除项目',
                //                        ]);
                //                    }
                //
                //                }
            } else if (!isset($data['quantity'])) {
                db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2, 'untime' => time()]);
                if ($data['yc'] == 1) {
                    //更新金额到沟通表
                    $res2 = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                    db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->update(['amount' => $res2]);
                }

                if (isset($res1['envelopes_id']) && !empty($res1['envelopes_id'])) {
                    $allow = db('allow')->where(['order_id' => $res1['ordesr_id'], 'envelopes_id' => $res1['envelopes_id']])->find();
                    if ($allow) {
                        db('allow')->where('envelopes_id', $res1['envelopes_id'])->update(['capital_id' => implode(',', db('capital')->where('envelopes_id', $res1['envelopes_id'])->where('types', 1)->column('capital_id'))]);
                    }
                }
                //判断是否还有代购主材
                $capitals = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();//代购主材;
                if ($capitals > 0) {
                    db('order')->where(['order_id' => $res1['ordesr_id']])->update(['order_agency' => 1]);
                } else {
                    db('order')->where(['order_id' => $res1['ordesr_id']])->update(['order_agency' => 0]);
                    db('envelopes')->where(['envelopes_id' => $res1['envelopes_id']])->update(['purchasing_discount' => 0, 'purchasing_expense' => 0]);
                }
            }

            //yc等于1 远程成交的，取优惠金额
//            $thro = db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->order('th_time desc')->find();
//            if ($data['yc'] == 1) {
//                $ca = db('envelopes')->where(['through_id' => $thro['through_id']])->field('give_money,purchasing_discount')->find();
//            } else {
//                $ca = db('envelopes')->where(['ordesr_id' => $res1['ordesr_id'], 'through_id' => 0])->field('give_money,purchasing_discount')->find();
//            }

            //代购主材有事物所以先减掉
//            if ($res1['agency'] == 1) {
//                $caps = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
//                if ($ca['purchasing_discount'] != 0.000) {
//                    if (($caps * config('purchasing_discount')) < $ca['purchasing_discount']) {
//                        throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                    }
//                }
//
//            } else {
//                $to_price = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 0])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
//                if ($ca['give_money'] != 0.000) {
//                    if (($to_price * config('give_money')) < $ca['give_money']) {
//                        throw  new  Exception('优惠金额不能大于订单总价的10%');
//                    }
//                }
//
//            }

//

            db()->commit();
            if ($cap['state'] > 3) {
                $approv = Db::connect(config('database.zong'))->table('approval')->where('relation_id', $data['capital_id'])->where('type', 6)->find();
                if (!empty($approv)) {
                    Db::connect(config('database.zong'))->table('approval')->where('relation_id', $data['capital_id'])->where('type', 6)->delete();
                    db('capital')->where(['capital_id' => $data['capital_id']])->update(['modified_quantity' => 0]);
                }
                if (isset($data['quantity']) && $data['quantity'] != 0) {
                    db('capital')->where(['capital_id' => $data['capital_id']])->update(['approve' => 3, 'modified_quantity' => $data['quantity'], 'reason_for_deduction' => $data['reasonForDeduction']]);
                    $title = $res1['class_b'] . '减少方量到(' . $data['quantity'] . ')';
                    $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], 9);
                } else {
                    $title = $res1['class_b'] . '项目减项(' . $this->us['username'] . ')';
                    $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], 6);
                }

            } else {
                $this->pdf->put($res1['ordesr_id'], 1, $cap);

            }

            json_decode(sendOrder($res1['ordesr_id']), true);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /**
     * 基检跟新公共
     */
    public function up()
    {
        $data = Request::instance()->post();

        db()->startTrans();
        try {
            $caps    = db('order')->where(['order_id' => $data['ordesr_id']])->field('ification,planned,appointment,tui_jian,tui_role,pro_id,state')->find();
            $capital = db('capital')->where(['ordesr_id' => $data['ordesr_id'], 'types' => 1, 'enable' => 1])->field('to_price,agency')->select();
            $result  = [];
            foreach ($capital as $key => $info) {
                $result[$info['agency']][] = $info;
            }

//            if (isset($result[0]) && $result[0] != 0) {
//                $cap = array_sum(array_column($result[0], 'to_price'));
//                if (($cap * config('give_money')) < $data['give_money']) {
//                    throw  new  Exception('优惠金额不能大于订单总价的10%');
//                }
//            }

//            if (count($result) == 2) {
//                $cap = array_sum(array_column($result[1], 'to_price'));
//                if (($cap * config('purchasing_discount')) < $data['purchasing_discount']) {
//                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                }
//            }
            $cli       = new Client();
            $envelopes = db('envelopes')->where('envelopes_id', $data['envelopes_id'])->find();
            if ($envelopes['purchasing_discount'] != $data['purchasing_discount'] || $envelopes['purchasing_expense'] != $data['purchasing_expense']) {
                //（改变后的管理费-优惠）-（改变前的管理费-优惠）
                $moeny = ($data['purchasing_expense'] - $data['purchasing_discount']) - ($envelopes['purchasing_expense'] - $envelopes['purchasing_discount']);

                $list = json_encode(["order_id" => $data['ordesr_id'], "type" => 2, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);

            }
            if ($envelopes['give_money'] != $data['give_money'] || $envelopes['expense'] != $data['expense']) {
                $moeny = ($data['expense'] - $data['give_money']) - ($envelopes['expense'] - $envelopes['give_money']);
                $list  = json_encode(["order_id" => $data['ordesr_id'], "type" => 1, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);
            }
            $oi = ['wen_a' => $data['wen_a'],//一级分类
                'give_b' => substr($data['give_b'], 0, -1),//一级分类
                'gong' => $data['gong'], 'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                'purchasing_discount' => $data['purchasing_discount'], 'expense' => $data['expense'], 'purchasing_expense' => $data['purchasing_expense'],

            ];
            db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update($oi);
            $uss['order_id']       = $data['ordesr_id'];
            $uss['discount']       = $oi['give_money'];
            $uss['plan_work_time'] = $data['gong'];
            $result                = send_post(UIP_SRC . "/support-v1/order/edit", $uss);
            $results               = json_decode($result, true);

            if ($results['code'] == 200) {
                db()->commit();
                json_decode(sendOrder($data['ordesr_id']), true);
                $this->pdf->put($data['ordesr_id'], 1, $caps);
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /*
     * 修改报价清单
     */
    public function QuotationList()
    {
        $data = Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['class_b' => $data['class_b']]);
        r_date(null, 200);
    }

    /*
    * 修改报价清单
    */
    public function MarkCollaboration()
    {
        $data = Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['cooperation' => $data['cooperation']]);
        r_date(null, 200);
    }

    /**
     * 电子合同
     */
    public function sign()
    {
        $data = Request::instance()->post();
        $op   = db('sign')->join('order', 'order.order_id=sign.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->field('order.assignor,order.order_no,sign.*,user.number')->where(['sign.order_id' => $data['order_id']])->find();

        $share = 0;
        if (isset($data['share']) && $data['share'] == 1) {
            $share    = ['share' => 1];
            $contract = db('contract')->where(['orders_id' => $data['order_id']])->find();
            if (!empty($contract) && $contract['contracType'] == 1) {
                db('contract')->where(['orders_id' => $data['order_id']])->update(['contracType' => 2]);
            }
        }
        if ($op) {
            $userId = $this->us['user_id'];
            if ($op['assignor'] != $op['user_id']) {
                $userId = $op['assignor'];
            }

            db('sign')->where(['order_id' => $data['order_id']])->update(['confirm' => 3, 'autograph' => '', 'agency_img' => '', 'contractpath' => '']);
            if (!empty($data['paymentId'])) {
                db('payment')->where(['payment_id' => $data['paymentId']])->delete();
            }
            $sign = ['idnumber' => $data['idnumber'], 'username' => $data['username'], 'order_id' => $data['order_id'], 'user_id' => $userId, 'addtime' => strtotime($data['addtime']), 'uptime' => strtotime($data['uptime']), 'addres' => $data['addres'], 'autograph' => $data['autograph'], 'ding' => $data['ding'], 'zhong' => $data['zhong'], 'wei' => $data['wei'], 'b1' => $data['b1'], 'b2' => $data['b2'], 'explain' => $data['explain'], 'additional' => $data['additional'], 'additional_agent' => $data['additional_agent'], 'engineering' => implode(',', json_decode($data['engineering'])), 'con_time' => time(), 'contract' => $op['order_no'], 'overdue_days' => $data['overdueDays']];
            if ($op['confirm'] == 2) {
                $sign['confirm'] = 3;
            }
            if (!empty($share)) {
                $sign = array_merge($sign, $share);
            }
            db('sign')->where(['order_id' => $data['order_id']])->update($sign);
            $id = $op['sign_id'];
        } else {
            $order_no = db('order')->where(['order_id' => $data['order_id']])->value('order_no');
            $sign     = ['idnumber' => $data['idnumber'], 'contract' => $order_no, 'username' => $data['username'], 'order_id' => $data['order_id'], 'user_id' => $this->us['user_id'], 'addtime' => strtotime($data['addtime']), 'uptime' => strtotime($data['uptime']), 'addres' => $data['addres'], 'autograph' => isset($data['autograph']) ? $data['autograph'] : '', 'ding' => $data['ding'], 'zhong' => $data['zhong'], 'wei' => $data['wei'], 'b1' => $data['b1'], 'b2' => $data['b2'], 'explain' => $data['explain'], 'additional' => $data['additional'], 'additional_agent' => $data['additional_agent'], 'engineering' => implode(',', json_decode($data['engineering'])), 'con_time' => time(), 'overdue_days' => isset($data['overdueDays']) ? $data['overdueDays'] : 0];
            if (!empty($share)) {
                $sign = array_merge($sign, $share);
            }
            $id = db('sign')->insertGetId($sign);
        }
        sendOrder($data['order_id']);


        r_date($id, 200);
    }

    /**
     * 电子报价合同确认提交
     */
    public function ContractView()
    {
//        $data = Request::instance()->post();
//        db('sign')->where(['sign_id' => $data['id']])->update(['contractpath' => $data['img'] . '?t=' . time(), 'confirm' => 1, 'agency_img' => isset($data['agency_img']) ? $data['agency_img'] : '']);
        r_date(1, 200);
    }

    /**
     * 老板基建报价显示
     */
    public function xian(Capital $capitals)
    {
        $data = Request::instance()->post();
        $op   = db('order')->where(['order.order_id' => $data['order_id']])
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->join('contract co', 'order.order_id=co.orders_id', 'left')
            ->field('sign.sign_id,sign.username,sign.idnumber,sign.contract,sign.addtime,sign.uptime,sign.addres,sign.contractpath,sign.agency_img,sign.ding,sign.zhong,sign.wei,sign.b1,sign.b2,sign.explain,sign.additional,sign.additional_agent,order.contacts,order.order_agency,order.quotation,co.con_time')
            ->find();

        $op['username']   = $op['contacts'];
        $op['idnumber']   = !empty($op['idnumber']) ? $op['idnumber'] : null;
        $op['contract']   = !empty($op['contract']) ? $op['contract'] : null;
        $op['type']       = !empty($op['contractpath']) ? 1 : 2;
        $op['addtime']    = !empty($op['addtime']) ? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']     = !empty($op['uptime']) ? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']     = !empty($op['addres']) ? $op['addres'] : null;
        $op['quotation']  = !empty($op['quotation']) ? $op['quotation'] : '';
        $op['agency_img'] = !empty($op['agency_img']) ? $op['agency_img'] : '';
        $capital          = $capitals
            ->with('specsList')
            ->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'types' => 1])
            ->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance,projectRemark,envelopes_id,cooperation,capital.reason_for_deduction as reasonForDeduction,ifnull(categoryName,"默认分组") as categoryName')
            ->select();
        if (!empty($capital)) {
            $envelopes = db('envelopes')->where(['envelopes_id' => $capital[0]['envelopes_id']])->find();
            $s         = implode(',', array_column($capital, 'capital_id'));
            $yc        = empty($envelopes['through_id']) ? 1 : 2;
            $agency    = [];
            foreach ($capital as $k => $item) {
                $item['specsList'] = $item['specs_list'];
                unset($item['specs_list']);
                if ($item['agency'] == 1) {
                    $agency[] = $item;
                }
                $capital[$k]['approve']         = 0;
                $capital[$k]['approval_reason'] = '';
                $capital[$k]['username']        = '';
            }
            $allow              = db('allow')->where(['order_id' => $data['order_id'], 'capital_id' => $s, 'envelopes_id' => $envelopes['envelopes_id'], 'yc' => $yc])->find();
            $envelopes['allow'] = $allow['id'];
            if (!empty($envelopes['give_b'])) {
                $envelopes['give_b'] = explode(',', $envelopes['give_b']);
            } else {
                $envelopes['give_b'] = null;
            }
            if ($envelopes['capitalgo']) {
                $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
            } else {
                $envelopes['capitalgo'] = null;
            }
            $envelopes['project_title']   = empty($envelopes['project_title']) ? '报价方案' : $envelopes['project_title'];
            $payment                      = \db('payment')->where(['weixin' => 1, 'orders_id' => $data['order_id']])->field('material,agency_material,payment_id')->order('payment_id desc')->find();
            $envelopes['material']        = empty($payment) ? null : $payment['material'];
            $envelopes['agency_material'] = empty($payment) ? null : $payment['agency_material'];
            $envelopes['paymentId']       = empty($payment) ? null : $payment['payment_id'];
            $envelopes['yc']              = $yc;
            $agency                       = count($agency);
            $envelopes['order_agency']    = empty($agency) ? 0 : 1;
            if (!empty($op['con_time'])) {
                $envelopes['incDesSignature'] = db('capital')->where('ordesr_id', $data['order_id'])->where(function ($query) use ($op) {
                    $query->where(['types' => 2, 'untime' => ['>', $op['con_time']]])->whereOr('increment=1  and crtime >' . $op['con_time']);
                })->where('signed', 0)->count();
            } else {
                $envelopes['incDesSignature'] = 0;
            }
            $pay                   = db('payment')->where(['weixin' => ['<>', 1], 'orders_id' => $data['order_id']])->field('money')->order('payment_id desc')->find();
            $envelopes['payMoney'] = empty($pay) ? 0 : $pay['money'];
        }

        $op = ['user' => $op, 'gong' => empty($envelopes) ? [] : $envelopes, 'company' => $capital];


        r_date($op, 200);
    }

    /**
     * 新版基建报价界面显示
     */
    public function ViewScheme()
    {
        $data = Request::instance()->post();
        $op   = db('order')->where(['order.order_id' => $data['order_id']])
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->field('sign.sign_id,sign.username,sign.idnumber,sign.contract,sign.addtime,sign.uptime,sign.addres,sign.contractpath,sign.agency_img,sign.ding,sign.zhong,sign.wei,sign.b1,sign.b2,sign.explain,order.contacts,order.quotation')
            ->find();

        $op['username']   = $op['contacts'];
        $op['idnumber']   = !empty($op['idnumber']) ? $op['idnumber'] : null;
        $op['contract']   = !empty($op['contract']) ? $op['contract'] : null;
        $op['type']       = !empty($op['contractpath']) ? 1 : 2;
        $op['addtime']    = !empty($op['addtime']) ? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']     = !empty($op['uptime']) ? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']     = !empty($op['addres']) ? $op['addres'] : null;
        $op['quotation']  = !empty($op['quotation']) ? $op['quotation'] : '';
        $op['agency_img'] = !empty($op['agency_img']) ? $op['agency_img'] : '';
        $envelopes        = db('envelopes')->where(['envelopes_id' => $data['envelopes_id']])->find();

        $capital = db('capital')->where(['envelopes_id' => $data['envelopes_id'], 'types' => 1])
            ->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance,projectRemark,approve,approval_reason,concat(capital.reason_for_deduction,if(capital.modified_quantity=0,"",",减量:"),if(capital.modified_quantity=0,"",round(capital.square-capital.modified_quantity,2))) as reasonForDeduction,modified_quantity')
            ->select();
        foreach ($capital as $k => $item) {
            $typeCapital ['approval.type'] = 6;
            if ($item['modified_quantity'] != 0) {
                $typeCapital['approval.type'] = array(['=', 6], ['=', 8], 'or');
            }
            $capital[$k]['username'] = \db('approval', config('database.zong'))
                ->join(config('database.zong')['database'] . '.bi_user', 'approval.nxt_id=bi_user.user_id', 'left')
                ->where($typeCapital)
                ->where('approval.relation_id', $item['capital_id'])
                ->value('bi_user.username');

        }
        $s     = implode(',', array_column($capital, 'capital_id'));
        $yc    = empty($envelopes['through_id']) ? 1 : 2;
        $allow = db('allow')->where(['order_id' => $data['order_id'], 'capital_id' => $s, 'envelopes_id' => $envelopes['envelopes_id'], 'yc' => $yc])->value('id');

        $envelopes['allow'] = $allow['id'];
        if (!empty($envelopes['give_b'])) {
            $envelopes['give_b'] = explode(',', $envelopes['give_b']);
        } else {
            $envelopes['give_b'] = null;
        }
        if ($envelopes['capitalgo']) {
            $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
        } else {
            $envelopes['capitalgo'] = null;
        }
        $envelopes['project_title'] = empty($envelopes['project_title']) ? '报价方案' : $envelopes['project_title'];
        $envelopes['yc']            = $yc;
        $op                         = ['user' => $op, 'gong' => $envelopes, 'company' => $capital,];


        r_date($op, 200);
    }


    /*
     * 基建添加备注
     */
    public function giveRemarks()
    {
        $data = Request::instance()->post();
        db('capital')->where(['capital_id' => $data['capital_id']])->update(['projectRemark' => $data['projectRemark']]);
        r_date('', 200);
    }

    /**
     * 基检
     */
    public function add_jian(Common $common)
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $cap = '';
            \db('envelopes')->where('ordesr_id', $data['order_id'])->update(['type' => 0]);
            \db('capital')->where('ordesr_id', $data['order_id'])->update(['enable' => 0]);
            \db('through')->where('order_ids', $data['order_id'])->update(['baocun' => 0]);
            \db('warranty_collection')->where('order_id', $data['order_id'])->update(['type' => 0]);
            if ($data['company']) {
                $op = json_decode($data['company'], true);

                foreach ($op as $ke => $v) {
                    $users = [];
                    if ($v['types'] == 0) {
                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        if ($product_chan) {
                            $users = ['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                                'square' => $v['fang'],//方量
                                'un_Price' => $product_chan['prices'],//单价
                                'rule' => $product_chan['price_rules'],//规则
                                'zhi' => $v['zhi'],//质保
                                'types' => 1,//状态
                                'fen' => 0,//状态
                                'to_price' => $product_chan['prices'] * $v['fang'],//总价
                                'crtime' => time(), 'ordesr_id' => $data['order_id'], 'class_a' => $v['title'],//三
                                'class_b' => $v['projectTitle'],//三
                                'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '',
                                'enable' => 1,//三
                                'programme' => 1,//三
                                'projectId' => $v['product_id'],//三
                                'gold_suite' => 1,//三
                                'agency' => $v['agency'],//三

                            ];
                        }

                    } elseif ($v['types'] == 1) {
                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        if ($product_chan) {
                            $users = ['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                                'square' => $v['fang'],//方量
                                'un_Price' => $product_chan['artificial'],//单价
                                'rule' => $product_chan['rmakes'],//规则
                                'zhi' => $v['zhi'],//质保
                                'types' => 1,//状态
                                'fen' => 1,//状态
                                'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                                'crtime' => time(), 'ordesr_id' => $data['order_id'], 'class_a' => $v['title'],//三
                                'class_b' => $v['projectTitle'],//三
                                'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '', 'enable' => 1,//三
                                'programme' => 1,//三
                                'projectId' => $v['product_id'],//三
                                'gold_suite' => $v['type'],//三
                                'agency' => $v['agency'],//三
                            ];
                        }


                    } elseif ($v['types'] == 2) {
                        $users = ['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'ordesr_id' => $data['order_id'], 'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'crtime' => time(), 'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '',
                            'enable' => 1,//三
                            'programme' => 1,//三
                            'projectId' => $v['product_id'],//三
                            'gold_suite' => 1,//三
                            'agency' => $v['agency'],//三
                        ];

                    }

                    if (!empty($users)) {
                        if ($v['agency'] == 1) {
                            $p1[] = $users['to_price'];
                        } else {
                            $p[] = $users['to_price'];
                        }
                        $id = db('capital')->insertGetId($users);

                        $cap .= $id . ',';
                        $c   = substr($cap, 0, -1);

                        $standardId = json_decode($data['standardId'], true);
                        if (isset($data['schemeId'])) {
                            foreach ($standardId as $item) {
                                foreach ($item['data'] as $value) {
                                    if ($v['product_id'] == $item['auxiliary_id']) {
                                        $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $value['id'], 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                        foreach ($value['data'] as $datum) {
                                            if ($datum['isChoose']) {
                                                db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum['id'], 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                            }

                                        }

                                    }
                                }

                            }

                        } else {
                            foreach ($standardId as $item) {
                                foreach ($item['auxiliaryInteractiveId'] as $value) {
                                    if ($v['product_id'] == $value['detailed_id']) {
                                        $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item['id'], 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                        foreach ($item['data'] as $datum) {
                                            if ($datum['isChoose']) {
                                                db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum['id'], 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                            }

                                        }

                                    }
                                }

                            }
                        }

                    }
                }

            }


            //总金额
            if (isset($p) && !empty($p)) {
                $o = round(array_sum($p), 2);
//                if (($o * config('give_money')) < $data['give_money']) {
//                    throw  new  Exception('优惠金额不能大于订单总价的10%');
//                }
            } else {
                if ($data['give_money'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                if ($data['expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }

            }
            if (isset($p1) && !empty($p1)) {
//                $o = round(array_sum($p1), 2);
//                if (($o * config('give_money')) < $data['purchasing_discount']) {
//                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                }
            } else {
                if ($data['purchasing_discount'] != 0) {
                    throw new Exception('代购合同没有清单');
                }
                if ($data['purchasing_expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }

            }

            $envelopes = db('envelopes')->insertGetId(['wen_a' => $data['wen_a'],//一级分类
                'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '', 'ordesr_id' => $data['order_id'], 'gong' => $data['gong'], 'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '', 'project_title' => $data['project_title'], 'expense' => !empty($data['expense']) ? $data['expense'] : 0, 'purchasing_discount' => $data['purchasing_discount'], 'purchasing_expense' => !empty($data['purchasing_expense']) ? $data['purchasing_expense'] : 0, 'type' => 1,

            ]);

            if (isset($data['schemeId']) && $data['schemeId'] != 0) {
                db('scheme_use', config('database.zong'))->insert(['plan_id' => $data['schemeId'], 'user_id' => $this->us['user_id'], 'creation_time' => time(), 'city' => config('cityId'), 'order_id' => $data['order_id'], 'envelopes_id' => $envelopes]);
            }

            \db('capital')->whereIn('capital_id', $c)->update(['envelopes_id' => $envelopes]);
            if (!empty($data['give_remarks'])) {
                db('through')->insertGetId(['mode' => '电话', 'amount' => 0, 'role' => 2, 'admin_id' => $this->us['user_id'], 'remar' => $data['give_remarks'], 'order_ids' => $data['order_id'], 'baocun' => 0, 'th_time' => time(), 'end_time' => 0, 'log' => '',//图片
                ]);
            }
            if (!empty($data['Warranty'])) {
                $Warranty = json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id' => $data['order_id'], 'warranty_id' => $value['warranty_id'], 'years' => $value['years'], 'creation_time' => time(), 'type' => 1, 'envelopes_id' => $envelopes]);
                }
            }

            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment,telephone')->find();
            if (preg_match("/^1[345678]{1}\d{9}$/", $cap['telephone'])) {
                sendMsg($cap['telephone'], 8615);
            }
            db('order')->where(['order_id' => $data['order_id']])->update(['undetermined' => 0, 'ification' => 2, 'agency_address' => isset($data['agency_address']) ? $data['agency_address'] : '']);

            $pdf = $this->pdf->put($data['order_id'], 2, $cap);
//            $pdf=true;
            db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime' => substr($data['startTime'], 0, -3), 'endTime' => substr($data['endTime'], 0, -3), 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);
            //报价及时性
            db('quote')->insertGetId(['startTime' => $cap['appointment'], 'planned' => $cap['planned'], 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);

            if ($pdf) {
                db()->commit();
                (new PollingModel())->automatic($data['order_id'], time());
                json_decode(sendOrder($data['order_id']), true);
                $clock_in = db('clock_in')->where('order_id', $data['order_id'])->value('order_id');
                if ($clock_in) {
                    $common->toExamine(1, $data['order_id'], 1, '');
                }
                r_date(null, 200);
            }

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }


    /**
     * 基建自定义历史列表
     */
    public function information()
    {
        $data = Request::instance()->post();
        if ($data['type'] == 1) {
            $object = db('information')->where(['types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes,agency')->select();
            foreach ($object as $k => $l) {
                $pr[$k]['projectId']    = $l['id'];
                $pr[$k]['projectMoney'] = $l['un_Price'];
                $pr[$k]['projectTitle'] = $l['class_b'];
                $pr[$k]['title']        = $l['company'];
                $pr[$k]['tao']          = $l['fen'];
                $pr[$k]['agency']       = $l['agency'];
                unset($object[$k]);
            }
            $pr = !empty($pr) ? $pr : null;
        } else {
            $object = db('information')->where(['id' => $data['id'], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes,agency')->find();

            $pr['projectId']    = $object['id'];
            $pr['projectMoney'] = $object['un_Price'];
            $pr['projectTitle'] = $object['class_b'];
            $pr['title']        = $object['company'];
            $pr['tao']          = $object['fen'];
            $pr['agency']       = $object['agency'];
        }

        r_date($pr, 200);
    }

    /*
     *
     * 增加自定义历史记录
     */
    public function inf_add()
    {

        $data = Request::instance()->post();

        $op   = db('information')->insertGetId(['company' => $data['unit'],//单位
            'square' => $data['fang'],//方量
            'un_Price' => $data['projectMoney'],//单价
            'zhi' => $data['zhi'],//质保
            'types' => 1,//状态
            'fen' => 3,//状态
            'to_price' => $data['fang'] * $data['projectMoney'],//总价
            'crtime' => time(), 'user_id' => $this->us['user_id'], 'class_a' => $data['title'],//三
            'class_b' => $data['projectTitle'],//三
            'qi_rmakes' => $data['qi_rmakes'], 'agency' => isset($data['agency']) ? $data['agency'] : 0, 'agency_id' => isset($data['agency_id']) ? $data['agency_id'] : 0,]);
        $data = ['id' => $op,];
        r_date($data, 200);
    }

    /*
     *
     * 删除自定义历史记录
     */
    public function inf_dell()
    {

        $data = $this->model->post(['id']);

        $p = db('information')->where('id', $data['id'])->update(['types' => 2]);
        if ($p) {
            r_date([], 200);
        }
        r_date([], 300);
    }


    /**
     * 远程沟通外面
     */
    public function gou()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $cap = '';
            \db('envelopes')->where('ordesr_id', $data['order_id'])->update(['type' => 0]);
            \db('capital')->where('ordesr_id', $data['order_id'])->update(['enable' => 0]);
            \db('through')->where('order_ids', $data['order_id'])->update(['baocun' => 0]);
            \db('warranty_collection')->where('order_id', $data['order_id'])->update(['type' => 0]);
            if ($data['company']) {
                $op = json_decode($data['company'], true);
                foreach ($op as $ke => $v) {
                    if ($v['types'] == 0) {

                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users        = ['wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['prices'],//单价
                            'rule' => $product_chan['price_rules'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 0,//状态
                            'to_price' => $product_chan['prices'] * $v['fang'],//总价
                            'capitalgo' => '',//优惠金额
                            'ordesr_id' => $data['order_id'], 'give_a' => '',//赠送项目
                            'give_b' => '', 'gong' => '', 'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '', 'enable' => $data['baocun'],//三
                            'programme' => 3,//三
                            'projectId' => $v['product_id'],//三
                            'gold_suite' => $v['type'],//三
                            'agency' => $v['agency'],//三
                        ];
                    } elseif ($v['types'] == 1) {

                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users        = ['wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['artificial'],//单价
                            'rule' => $product_chan['rmakes'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 1,//状态
                            'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                            'capitalgo' => '',//优惠金额
                            'ordesr_id' => $data['order_id'], 'give_a' => '',//赠送项目
                            'give_b' => '', 'gong' => '', 'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '', 'enable' => $data['baocun'],//三
                            'programme' => 3,//三
                            'projectId' => $v['product_id'],//三
                            'gold_suite' => $v['type'],//三
                            'agency' => $v['agency'],//三
                        ];
                    } elseif ($v['types'] == 2) {

                        $users = ['wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'capitalgo' => '',//优惠金额
                            'ordesr_id' => $data['order_id'], 'give_a' => '',//赠送项目
                            'give_b' => '', 'gong' => '', 'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '', 'enable' => $data['baocun'],//三
                            'programme' => 3,//三
                            'projectId' => $v['product_id'],//三
                            'gold_suite' => 1,//三
                            'agency' => $v['agency'],//三
                        ];
                    }
                    if ($v['agency'] == 1) {
                        $p1[] = $users['to_price'];
                    } else {
                        $p[] = $users['to_price'];
                    }

                    if (isset($v['capital_id']) && $v['capital_id'] != 0) {
                        db('capital')->where('capital_id', $v['capital_id'])->update($users);

                    } else {
                        $users['crtime'] = time();
                        $capital         = db('capital')->insertGetId($users);
                        $cap             .= $capital . ',';
                        $c               = substr($cap, 0, -1);
                        $standardId      = json_decode($data['standardId'], true);
                        foreach ($standardId as $item) {
                            foreach ($item['auxiliaryInteractiveId'] as $value) {
                                if ($v['product_id'] == $value['detailed_id']) {
                                    $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item['id'], 'capital_id' => $capital, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                    foreach ($item['data'] as $datum) {
                                        if ($datum['isChoose']) {
                                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum['id'], 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                        }
                                    }

                                }
                            }
                        }

                    }

                }
            }

            $o1 = 0;
            $o2 = 0;
            if (isset($p) && !empty($p)) {
                $o1 = round(array_sum($p), 2);
//                if (($o1 * config('give_money')) < $data['give_money']) {
//                    throw new Exception('优惠金额不能大于订单总价的10%');
//                }
            } else {
                if ($data['give_money'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                if ($data['expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }
            }
            if (isset($p1) && !empty($p1)) {
//                $o2 = round(array_sum($p1), 2);
//                if (($o2 * config('purchasing_discount')) < $data['purchasing_discount']) {
//                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
//                }
            } else {
                if (($data['purchasing_discount']) != 0) {
                    throw new Exception('代购合同没有清单');
                }
                if (($data['purchasing_expense']) != 0) {
                    throw new Exception('代购合同没有清单');
                }
            }

            $o = $o1 + $o2;
            if ($data['baocun'] == 1) {
                $cheng = 1;
            } else {
                $cheng = 0;
            }

            if (!empty($data['through_id'])) {
                if (!empty($c)) {
                    $c = $data['capital_id'] . ',' . $c;
                } else {
                    $c = $data['capital_id'];
                }
                $warranty_collection = \db('warranty_collection')->where('through_id', $data['through_id'])->find();
                if ($warranty_collection) {
                    \db('warranty_collection')->where('through_id', $data['through_id'])->update(['type' => 1]);
                }

                db('through')->where('through_id', $data['through_id'])->update(['mode' => $data['mode'], 'amount' => $o, 'remar' => $data['give_remarks'], 'order_ids' => $data['order_id'], 'admin_id' => $this->us['user_id'], 'baocun' => $data['baocun'], 'th_time' => time(), 'end_time' => strtotime($data['end_time']), 'log' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id' => !empty($c) ? $c : '',]);
                db('envelopes')->where('through_id', $data['through_id'])->update(
                    [
                        'wen_a' => $data['wen_a'],//一级分类
                        'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '',
                        'ordesr_id' => $data['order_id'], 'give_remarks' => $data['give_remarks'],//备注
                        'gong' => $data['gong'], 'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',
                        'give_money' => $data['give_money'],//优惠金额
                        'project_title' => $data['project_title'], 'expense' => !empty($data['expense']) ? $data['expense'] : 0,
                        'purchasing_discount' => $data['purchasing_discount'],
                        'purchasing_expense' => !empty($data['purchasing_expense']) ? $data['purchasing_expense'] : 0, 'type' => $cheng,]);
                if ($data['id']) {
                    db('allow')->where('id', $data['id'])->update(['capital_id' => $c]);
                }
                $envelopes_id = db('envelopes')->where('through_id', $data['through_id'])->value('envelopes_id');
                db('capital')->whereIn('capital_id', $c)->update(['envelopes_id' => $envelopes_id, 'deal' => 1]);
            } else {

                $p = db('through')->insertGetId(['mode' => $data['mode'], 'amount' => $o, 'remar' => $data['give_remarks'], 'order_ids' => $data['order_id'], 'admin_id' => $this->us['user_id'], 'baocun' => $data['baocun'], 'th_time' => time(), 'end_time' => strtotime($data['end_time']), 'log' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id' => !empty($c) ? $c : '',

                ]);

                $envelopes = db('envelopes')->insertGetId(['wen_a' => $data['wen_a'],//一级分类
                    'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '', 'ordesr_id' => $data['order_id'], 'gong' => $data['gong'], 'give_remarks' => $data['give_remarks'],//备注
                    'give_money' => $data['give_money'],//优惠金额
                    'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',
                    'through_id' => $p,
                    'project_title' => $data['project_title'],
                    'expense' => !empty($data['expense']) ? $data['expense'] : 0,
                    'purchasing_discount' => $data['purchasing_discount'],
                    'purchasing_expense' => !empty($data['purchasing_expense']) ? $data['purchasing_expense'] : 0,
                    'type' => $cheng,]);
                db('capital')->whereIn('capital_id', $c)->update(['envelopes_id' => $envelopes, 'deal' => 1]);
                if (!empty($data['Warranty'])) {
                    $Warranty = json_decode($data['Warranty'], true);
                    if (!empty($Warranty)) {
                        foreach ($Warranty as $value) {
                            \db('warranty_collection')->insertGetId(['order_id' => $data['order_id'], 'warranty_id' => $value['warranty_id'], 'years' => $value['years'], 'creation_time' => time(), 'through_id' => $p, 'type' => $data['baocun'], 'envelopes_id' => $envelopes]);
                        }
                    }
                }
            }

            $s  = db('through')->where('order_ids', $data['order_id'])->column('through_id');
            $us = db('order')->where('order_id', $data['order_id'])->find();
            if ($data['baocun'] == 1 && $us['state'] < 4) {
                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'state' => 3, 'undetermined' => 0, 'ification' => 2, 'update_time' => time(), 'agency_address' => isset($data['agency_address']) ? $data['agency_address'] : $us['agency_address']]);


                remind($data['order_id'], 3);
            }


            if ($data['baocun'] == 0) {
                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'ification' => 2, 'update_time' => time()]);
                if ($us['state'] == 1) {
                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'state' => 2, 'undetermined' => 1, 'ification' => 2, 'update_time' => time(), 'agency_address' => isset($data['agency_address']) ? $data['agency_address'] : '', 'undetermined_time' => time()]);
                }

            }
            $message = db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
            }
            $remind = db('remind')->where(['order_id' => $data['order_id'], 'admin_id' => $this->us['user_id']])->find();
            if ($remind['tai'] != 0) {
                db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['tai' => 0]);
            }
            $this->pdf->put($data['order_id'], 2, $us);

            db()->commit();
            json_decode(sendOrder($data['order_id']), true);
            (new PollingModel())->automatic($data['order_id'], time());

            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /**
     * 远程沟通删除
     */
    public function deletion()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if (!empty($data['through_id'])) {
                $p        = db('through')->where('through_id', $data['through_id'])->field('capital_id,order_ids')->find();
                $order_id = $p['order_ids'];
                db('capital')->where(['capital_id' => ['in', $p['capital_id']]])->update(['types' => 2]);
                db('through')->where('through_id', $data['through_id'])->update(['capital_id' => '']);
                db('envelopes')->where('through_id', $data['through_id'])->update(['delete_time' => time()]);
            } else {
                $order_id = db('envelopes')->where('envelopes_id', $data['envelopes_id'])->value('ordesr_id');
                db('capital')->where(['envelopes_id' => $data['envelopes_id']])->update(['types' => 2]);

                db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['delete_time' => time()]);
            }
            $op = db('allow')->where('envelopes_id', $data['envelopes_id'])->find();
            if ($op) {
                db('allow')->where('envelopes_id', $data['envelopes_id'])->delete();
            }
            db()->commit();
            json_decode(sendOrder($order_id), true);
            r_date('', 200, '删除成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /**
     * 远程沟通列表
     */
    public function gou_list()
    {
        $data = $this->model->post(['page' => 1, 'limit' => 10, 'order_ids']);
        $ca   = db('envelopes')->where(['ordesr_id' => $data['order_ids']])->where('delete_time', 0)->page($data['page'], $data['limit'])->select();
        $da   = [];
        foreach ($ca as $k => $item) {
            $cap                     = db('capital')->where(['envelopes_id' => $item['envelopes_id'], 'types' => 1])->field('sum(to_price) as to_price,crtime,envelopes_id,fen')->select();
            $da[$k]['amount']        = sprintf('%.2f', $cap[0]['to_price'] + ($item['expense'] + $item['purchasing_expense']) - ($item['give_money'] + $item['purchasing_discount']));
            $da[$k]['project_title'] = empty($item['project_title']) ? '远程报价方案' : $item['project_title'];
            $da[$k]['th_time']       = date('Y-m-d H:i:s', $cap[0]['crtime']);
            $da[$k]['yc']            = $item['through_id'];
            $da[$k]['through_id']    = $item['through_id'];
            $da[$k]['envelopes_id']  = $item['envelopes_id'];
            $da[$k]['type']          = $item['type'];
            $old                     = 0;
            if ($cap[0]['fen'] == 4) {
                $old = 1;
            }
            $da[$k]['old'] = $old;
            unset($da[$k]['capital_id']);
        }
        r_date($da, 200);
    }

    /**
     * 报价确认成交
     */
    public function FinalSelection(OrderModel $orderModel, Capital $capital)
    {
        $data = $this->model->post(['order_ids', 'yc', 'envelopes_id']);
        $main_mode_type1 = db('sign')->where('order_id', $data['order_ids'])->field('autograph,confirm')->find();
        $state = db('order')->where('order_id', $data['order_ids'])->value('state');
        if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
            db('sign')->where('order_id', $data['order_ids'])->delete();
        }
        if(!empty($main_mode_type1['autograph']) && $state==3){
            r_date('', 300, '合同已签字不允许切换报价');
        }
        $orderModel->MultiTableUpdate($data['order_ids'], 0);
        if ($data['yc'] != 0) {
            \db('through')->where('through_id', $data['yc'])->update(['baocun' => 1]);

        }
        \db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['type' => 1]);
        \db('capital')->where('envelopes_id', $data['envelopes_id'])->update(['enable' => 1]);
        \db('warranty_collection')->where('envelopes_id', $data['envelopes_id'])->update(['type' => 1]);
        $capitals = $capital->whetherAgency(['envelopes_id' => $data['envelopes_id'], 'types' => 1, 'enable' => 1, 'agency' => 1]);
        if ($capitals > 0) {
            $listOrderType = 1;
        } else {
            $listOrderType = 0;
        }
        $orderModel->orderAgency(['order_id' => $data['order_ids'], 'order_agency' => $listOrderType]);
       
        $orderSMS = json_decode(sendOrder($data['order_ids']), true);
        if ($orderSMS['code'] != 200) {
            r_date('', 300, '编辑失败');
        }
        r_date('', 200);
    }

    /**
     * 远程沟通里面
     */
    public function gou2()
    {

        $data = $this->model->post(['remar', 'order_id', 'end_time', 'mode', 'log', 'isPending']);
        db()->startTrans();
        try {
            $t = ['mode' => $data['mode'], 'amount' => 0, 'role' => 2, 'admin_id' => $this->us['user_id'], 'remar' => $data['remar'], 'order_ids' => $data['order_id'], 'baocun' => 0, 'th_time' => time(), 'end_time' => strtotime($data['end_time']), 'log' => !empty($data['log']) ? serialize(json_decode($data['log'], true)) : '',//图片
            ];
            db('through')->insertGetId($t);
            if ($data['isPending'] == 'true') {
                $message = db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
                if ($message['already'] != 0) {
                    db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
                    db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
                }
                $res = db('remind')->where(['order_id' => $data['order_id'], 'admin_id' => $this->us['user_id']])->value('tai');
                if ($res != 0) {
                    db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['tai' => 0]);
                }
                db('order')->where(['order_id' => $data['order_id']])->update(['undetermined' => 1, 'state' => 2, 'undetermined_time' => time()]);
            }
            $d = db('through')->where('order_ids', $data['order_id'])->select();
            $s = '';
            foreach ($d as $item) {
                $s .= $item['through_id'] . ',';
            }
            $s = substr($s, 0, -1);
            db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s]);
            db()->commit();
            json_decode(sendOrder($data['order_id']), true);
            (new PollingModel())->automatic($data['order_id'], time(), 2);
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /**
     * 远程沟通列表
     */
    public function get_gou()
    {
        $data = $this->model->post(['order_ids', 'gid']);
        $k    = db('through');
        if ($data['gid']) {
            if (strstr("店长", $data['gid'])) {
                $k->where(['role' => [['eq', 2], ['neq', 3]]]);
            } elseif (strstr("客服", $data['gid'])) {
                $k->where(['role' => [['eq', 1], ['neq', 3]]]);
            } elseif (strstr("客户", $data['gid'])) {
                $k->where(['role' => [['eq', 4], ['neq', 3]]]);
            } else {
                $k->where(['role' => [['eq', 6], ['neq', 3]]]);
            }
        } else {
            $k->where(['role' => ['neq', 3]]);
        }
        $h = $k->where(['order_ids' => $data['order_ids']])->order('th_time desc')->select();
        foreach ($h as $k => $value) {
            if ($value['log']) {
                $h[$k]['log'] = unserialize($value['log']);
            } else {
                $h[$k]['log'] = null;
            }
            $h[$k]['remar']   = !empty($value['remar']) ? $value['remar'] : '';
            $h[$k]['th_time'] = !empty($value['th_time']) ? date('Y-m-d H:i:s', $value['th_time']) : null;
        }
        r_date($h, 200);
    }


    /************************************************************** 订单列表**************************************************************/
    /*
     *   0"全部" 1"新订单"2"待处理"3"带上门"4"待签约"5"施工中"6"已完工"7"已收藏"8"已取消"9"退单"10"待结算"11"被投诉"
     */

    public function get_order(OrderModel $orderModel)
    {
        $data = $this->model->post();

        $m = $orderModel->table('order')->alias('a')
            ->field('a.order_id,a.rework,master_half_cost_time,a.ification,a.order_no,a.settlement_time,a.addres,a.contacts,a.telephone,a.remarks,a.lat,a.lng,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,a.finish_time,if(a.hardbound=0,go.title,concat(go.title,"(精装房)")) as title,co.con_time,co.contracType,co.dep_money,co.weixin,st.dep,st.con,st.up_time,st.sta_time,be.tail,a.point,cos.type,a.undetermined,me.time as message_time,a.cleared_time,comp.time,a.point_time,a.undetermined_time,a.start_time,a.finish_time,a.tui_time,order_aggregate.main_price,order_aggregate.agent_price')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('contract co', 'a.order_id=co.orders_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('message me', 'a.order_id=me.order_id and me.type=6 and a.assignor=me.user_id', 'left')
            ->join('cost cos', 'a.order_id=cos.order_id', 'left')
            ->join('complaint comp', 'a.order_id=comp.order_id', 'left')
            ->join('order_aggregate', 'a.order_id=order_aggregate.order_id', 'left')
            ->group('a.order_id');

        if (isset($data['title']) && $data['title'] != '') {
            $m->where(['a.contacts|a.telephone|a.addres|go.title' => ['like', "%{$data['title']}%"]]);
        }
        //创建时间
        if (isset($data['created_time']) && $data['created_time'] != '' && $data['created_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['created_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.created_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //预约时间
        if (isset($data['planned']) && $data['planned'] != '' && $data['planned'] != 0) {
            //本日
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            $m->where(['a.planned' => ['between', [$beginToday, $endToday]]]);
        }
        //签约时间
        if (isset($data['con_time']) && $data['con_time'] != '' && $data['con_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['con_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['co.con_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //开工时间
        if (isset($data['start_time']) && $data['con_time'] != '' && $data['start_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['start_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.start_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //完工时间
        if (isset($data['finish_time']) && $data['con_time'] != '' && $data['finish_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['finish_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.finish_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //完款时间
        if (isset($data['received_time']) && $data['received_time'] != '' && $data['received_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['received_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.con_time' => ['received_time', [strtotime($starttime), $enttime]]]);
        }
        //结算时间
        if (isset($data['cleared_time']) && $data['cleared_time'] != '' && $data['cleared_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['cleared_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.cleared_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        if (isset($data['state']) && $data['state'] != '' && $data['state'] != 0) {

            if ($data['state'] == 1) {
                $m->where(['a.state' => 1]);   //待结单
                $m->order('me.time desc');
            } elseif ($data['state'] == 2) {
                $m->where('a.through_id !=NULL or a.undetermined=1'); //带处理
                $m->where(['a.state' => ['<', 4]]);
                $m->order('a.undetermined_time desc');
            } elseif ($data['state'] == 3) {
                $m->where(['a.state' => 2]);  //带上门
                $m->order('a.planned desc');
            } elseif ($data['state'] == 4) {
                $m->where(['a.state' => 3]);  //待签约
                $m->order('a.order_id desc');
            } elseif ($data['state'] == 5) {
                $m->where(['a.state' => ['between', [4, 5]]]);   //施工中
                $m->order('co.con_time desc');
            } elseif ($data['state'] == 6) {
                $m->where(['a.state' => ['between', [6, 7]]]); //已完工
                $m->whereNull('a.cleared_time'); //已完工
                $m->whereNull('a.received_time'); //已完工
                $m->order('a.finish_time desc');
            } elseif ($data['state'] == 7) {

                $m->where(['a.point' => 2]);//已收藏
                $m->order('a.point_time desc');
            } elseif ($data['state'] == 8) {
                $m->where(['a.state' => 8]);  // 已取消
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 9) {
                $m->where(['a.state' => 9]);//已退单
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 10) {
                $m->where(['a.state' => ['between', [6, 7]]]); //已完工
//                $m->whereNull('a.cleared_time'); //已完工
                $m->where('if(order_aggregate.main_price=0,a.settlement_time IS NULL,a.cleared_time IS NULL)');
                $m->whereNotNull('a.received_time'); //已完工
                $m->order('a.received_time desc');
            } elseif ($data['state'] == 11) {
                $order_id = \db('complaint')->column('order_id');
                $m->whereIn('a.order_id', $order_id);//投诉订单
                $m->order('comp.time desc');
            } elseif ($data['state'] == 12) {
                $m->whereNotNull('a.cleared_time');//已结算
                $m->order('a.cleared_time desc');//已结算
            } elseif ($data['state'] == 13) {
                $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $order_id   = db('through')
                    ->where('role', 2)
                    ->where('admin_id', $this->us['user_id'])
                    ->whereBetween('end_time', [$beginToday, $endToday])->column('order_ids');
                $m->whereIn('a.order_id', $order_id);
            }
            //排除掉待处理订单
            if ($data['state'] != 7 && $data['state'] != 8 && $data['state'] != 9 && $data['state'] != 13) {
                if ($data['state'] != 2) {
                    $m->where(['a.undetermined' => 0]);
                } else {
                    $m->where(['a.undetermined' => 1]);
                }
            }

        } else {
            $m->where(['a.state' => ['neq', 10]]);
            $m->order('a.order_id desc');//已结算
        }
        if (isset($data['user_id']) && $data['user_id'] != 0) {
            $m->where(['a.assignor' => $data['user_id']]);
        } else {
            $m->where(['a.assignor' => $this->us['user_id']]);
        }
        if (isset($data['acceptance_time'])) {
            $m->whereNotNull('a.acceptance_time');
            $m->whereNull('a.settlement_time');
        }
        if (isset($data['settlement_time'])) {
            $m->whereNotNull('a.settlement_time');
        }
        if (isset($data['order_agency'])) {
            $m->where('a.order_agency', 1);
            $m->where('a.state', '>', 3);
            $m->whereNull('a.settlement_time');
            $m->whereNull('a.acceptance_time');
        }
        $list = $m->page($data['page'], $data['limit'])->select();
        foreach ($list as $k => $key) {
            $order_rework                  = db('order_rework')->where(['order_id' => $key['order_id']])->field('customer,reason as rewordDes,master_id')->order('id desc')->find();
            $list[$k]['customer']          = !empty($order_rework['customer']) ? $order_rework['customer'] : null;
            $list[$k]['rewordDes']         = !empty($order_rework['rewordDes']) ? $order_rework['rewordDes'] : null;
            $list[$k]['master_id']         = !empty($order_rework['master_id']) ? $order_rework['master_id'] : null;
            $list[$k]['con_time']          = !empty($key['con_time']) ? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['up_time']           = !empty($key['up_time']) ? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['start_time']        = !empty($key['start_time']) ? date('Y-m-d H:i:s', $key['start_time']) : '';
            $list[$k]['finish_time']       = !empty($key['finish_time']) ? date('Y-m-d H:i:s', $key['finish_time']) : '';
            $list[$k]['sta_time']          = !empty($key['sta_time']) ? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['created_time']      = !empty($key['created_time']) ? date('Y-m-d H:i', $key['created_time']) : '';
            $list[$k]['planned']           = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
            $list[$k]['tui_time']          = !empty($key['tui_time']) ? date('Y-m-d H:i:s', $key['tui_time']) : '';
            $list[$k]['time']              = !empty($key['time']) ? date('Y-m-d H:i:s', $key['time']) : '';
            $list[$k]['cleared_time']      = !empty($key['cleared_time']) ? date('Y-m-d H:i:s', $key['cleared_time']) : '';
            $list[$k]['point_time']        = !empty($key['point_time']) ? date('Y-m-d H:i:s', $key['point_time']) : '';
            $list[$k]['undetermined_time'] = !empty($key['undetermined_time']) ? date('Y-m-d H:i:s', $key['undetermined_time']) : '';
            $crtime                        = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->order('capital_id desc')->value('crtime');
            $list[$k]['crtime']            = !empty($crtime) ? date('Y-m-d H:i:s', $crtime) : '';
            $offer                         = $orderModel::offer($key['order_id']);
            $list[$k]['amount']            = $offer['amount'];
            if (empty($offer['amount'])) {
                $list[$k]['amount'] = sprintf("%.2f", $offer['agency']);
            }
            $list[$k]['payment'] = 1;
            if ($offer['yu'] < 0) {
                $list[$k]['payment'] = 2;
            }
            $list[$k]['yu']           = $offer['yu'];
            $list[$k]['yc']           = $offer['yc'];
            $list[$k]['gong']         = $offer['gong'];
            $list[$k]['message_time'] = put_time($key['message_time']);
            $list[$k]['agency']       = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();//代购主材;
            if (!empty($key['cleared_time']) && empty($list[$k]['agency'])) {
                $list[$k]['settlement'] = 1;
            } elseif (!empty($key['cleared_time']) && !empty($list[$k]['agency']) && !empty($list[$k]['settlement_time'])) {
                $list[$k]['settlement'] = 1;
            } elseif (!empty($key['cleared_time']) && !empty($list[$k]['agency']) && empty($list[$k]['settlement_time'])) {
                $list[$k]['settlement'] = 0;
            } else {
                $list[$k]['settlement'] = 0;
            }
            if (isset($data['state']) && $data['state'] == 11) {
                $list[$k]['complaint'] = 11;
            } else {
                $list[$k]['complaint'] = 0;
            }
            $i                    = db('through')->where(['order_ids' => $key['order_id'], 'role' => 2])->field('end_time,th_time')->order('through_id desc')->find();
            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
            $list[$k]['th_time']  = !empty($i['th_time']) ? date('Y-m-d H:i:s', $i['th_time']) : '';
            $list[$k]['remind']   = db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $key['order_id']])->value('tai');
        }

        if (isset($data['Test']) && $data['Test'] == 1) {
            res_date(array_merge($list));
        } else {
            r_date(array_merge($list));
        }

    }

    /*
     * 工作台中待沟通红点小时
     */
    public function workProcessing()
    {
        $data = $this->model->post();
        db('through')->where('order_ids', $data['order_id'])->update(['handle' => time()]);
        r_date(null, 200);
    }

    /**
     * 订单详情
     */
    public function get_info(OrderModel $orderModel, schemeMaster $schemeMaster)
    {

        $data = $this->model->post();
        if (empty($data['order_id'])) {
            r_date([], 300, '参数错误');
        }
        if (!empty($data['user_id'])) {
			$this->us['user_id'] = $data['user_id'];
        }
        $re = db('order')->field('order.order_id,order.hardbound,order.pro_id1,order.pro_id,order.settlement_time,order.master_half_cost_time,order.agency_address,order.ification,order.rework,order.logo,order.order_no,order.lat,order.lng,order.addres,order.contacts,order.telephone,order.remarks,order.created_time,order.state,order.quotation,order.entry,order.planned,p.province,c.city,y.county,go.title,go1.title as title3,co.con_time,co.type,co.weixin as weixin1,co.contract,co.contract_id,co.contracType,co.deposit,co.dep_money,co.main_material_img,st.invoice,st.sta_time,st.dep,st.con,st.up_time,st.sta_time,be.logos,be.tail,ac.full,order.label_id,order.point,re.tai,me.time as message_time,comp.reason,sin.contractpath,sin.autograph,order.cleared_time,order.finish_time,order.received_time,order.start_time,b.title as title1,channel_details.title as title2')
            ->join('chanel b', 'order.channel_id=b.id', 'left')
            ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('goods_category go1', 'order.pro_id1=go1.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('contract co', 'order.order_id=co.orders_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('product ac', 'order.product_id=ac.product_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->join('message me', 'order.order_id=me.order_id and me.type=6', 'left')
            ->join('remind re', 'order.order_id=re.order_id', 'left')
            ->join('sign sin', 'order.order_id=sin.order_id ', 'left')
            ->join('complaint comp', 'order.order_id=comp.order_id ', 'left');
        if (isset($data['type']) && $data['type'] != '') {
            $re->where(['u.reserve' => 2]);
        } else {

            $re->where(['order.assignor' => $this->us['user_id']]);
        }
        $res = $re->where(['order.order_id' => $data['order_id']])->find();


        if ($res) {
            $message = db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
            }
            if ($res['tai'] != 0) {
                db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['tai' => 0]);
            }
            $order_rework             = db('order_rework')->where(['order_id' => $data['order_id']])->field('customer,reason as rewordDes,master_id')->order('id desc')->find();
            $res['customer']          = !empty($order_rework['customer']) ? $order_rework['customer'] : null;
            $res['rewordDes']         = !empty($order_rework['rewordDes']) ? $order_rework['rewordDes'] : null;
            $res['master_id']         = !empty($order_rework['master_id']) ? $order_rework['master_id'] : null;
            $res['planned']           = !empty($res['planned']) ? date('Y-m-d H:i', $res['planned']) : null;
            $res['logo']              = !empty($res['logo']) ? unserialize($res['logo']) : null;
            $res['contract']          = !empty($res['contract']) ? unserialize($res['contract']) : null;
            $res['main_material_img'] = !empty($res['main_material_img']) ? unserialize($res['main_material_img']) : null;
            $res['autograph']         = !empty($res['autograph']) ? $res['autograph'] : null;
            $res['remarks']           = !empty($res['remarks']) ? $res['remarks'] . '录入人员：' . $res['entry'] : '录入人员：' . $res['entry'];
            $res['deposit']           = !empty($res['deposit']) ? unserialize($res['deposit']) : null;
            $res['sta_time']          = !empty($res['sta_time']) ? date('Y-m-d H:i', $res['sta_time']) : null;
            $res['inside']            = !empty($res['inside']) ? $res['inside'] : null;
            $res['up_time']           = !empty($res['up_time']) ? date('Y-m-d H:i', $res['up_time']) : null;
            $res['tui_time']          = !empty($res['tui_time']) ? date('Y-m-d H:i', $res['tui_time']) : null;
            $res['con_time']          = !empty($res['con_time']) ? date('Y-m-d H:i:s', $res['con_time']) : null;
            $res['created_time']      = !empty($res['created_time']) ? date('Y-m-d H:i', $res['created_time']) : null;
            $res['message_time']      = !empty($res['message_time']) ? date('Y-m-d H:i', $res['message_time']) : null;
            $res['uptime']            = !empty($res['uptime']) ? date('Y-m-d H:i', $res['uptime']) : null;
            $res['finish_time']       = !empty($res['finish_time']) ? date('Y-m-d H:i', $res['finish_time']) : null;
            $res['start_time']        = !empty($res['start_time']) ? date('Y-m-d H:i', $res['start_time']) : null;
            $res['received_time']     = !empty($res['received_time']) ? date('Y-m-d H:i', $res['received_time']) : null;
            $res['cleared_time']      = !empty($res['cleared_time']) ? date('Y-m-d H:i', $res['cleared_time']) : null;

            $res['settlement_time'] = !empty($res['settlement_time']) ? 1 : 0;

            $res['master_half_cost_time'] = !empty($res['master_half_cost_time']) ? $res['master_half_cost_time'] : 0;
            $res['pro_id1']               = !empty($res['pro_id1']) ? $res['pro_id1'] : 0;

            $res['channelTitle'] = $res['title1'] . '-' . $res['title2'];
            $res['yu']           = 0;
            $i                   = db('through')->where(['order_ids' => $data['order_id'], 'role' => 2])->field('end_time')->order('through_id desc')->find();
            $res['end_time']     = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : null;
            $shi['ids']          = $res['master_id'];
            if ($res['contracType'] == 0 && !empty($res['contract_id'])) {
                $res['contracType'] = 1;
            }
            if (!empty($shi['ids'])) {
                $results = send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                $results = json_decode($results, true);
                if ($results['code'] == 200) {
                    if (!empty($results['data'])) {
                        $res['master_username'] = $results['data'];
                    } else {
                        $res['master_username'] = null;
                    }
                } else {
                    $res['master_username'] = null;
                }

            } else {
                $res['master_username'] = null;
            }

            //签约金额
            $offer = $orderModel::offer($data['order_id']);

            $res['agency']         = sprintf("%.2f", $offer['agency']);//代购主材报价金额
            $res['auxiliaryState'] = $offer['auxiliaryState'];//代购主材报价金额

            $res['p'] = sprintf("%.2f", $offer['amount']);
            if (empty($offer['amount'])) {
                $res['p'] = sprintf("%.2f", $offer['agency']);
            }
            //材料领用
            $material_usage           = db('material_usage')->where('status', 1)->where(['order_id' => $data['order_id']])->sum('total_price');
            $material_material        = db('material_usage')->where(['order_id' => $data['order_id'], 'types' => 2, 'status' => 0])->sum('total_price');
            $res['material_usage']    = sprintf("%.2f", $material_usage);
            $res['material_material'] = sprintf("%.2f", $material_material);
            //费用报销
            $reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'status' => 1])->field('SUM(IF(classification=4,money,0)) as agent_payment_ok,SUM(IF(classification !=4,money,0)) as main_payment_ok')->select();


            $res['reimbursement']   = empty($reimbursement[0]['main_payment_ok']) ? 0 : $reimbursement[0]['main_payment_ok'];//费用报销
            $res['agency_sum']      = empty($reimbursement[0]['agent_payment_ok']) ? 0 : $reimbursement[0]['agent_payment_ok'];//代购报销
            $material_profit        = $res['agency'] - $res['agency_sum'];//主材利润
            $res['material_profit'] = sprintf("%.2f", $material_profit);
            $res['material_To']     = db('reimbursement')->where(['order_id' => $data['order_id'], 'type' => 2, 'status' => 0])->count();
            $res['yc']              = $offer['yc'];
            $res['remainingAmount'] = sprintf("%.2f", $res['p'] - $offer['yu'] - $offer['auditedAmount']);
            $res['auditedAmount']   = sprintf("%.2f", $offer['auditedAmount']);
            $res['rejectMoney']     = sprintf("%.2f", $offer['rejectMoney']);
            $res['payment']         = 1;
            $res['paymentTitle']    = '录入金额';
            $res['system_time']     = time();
            $res['yu']              = sprintf('%.2f', $offer['yu']);
            $pa                     = db('payment')->where(['orders_id' => $res['order_id']])->order('payment_id desc')->field('money,weixin,agency_material,material,pay_type,payment_id')->find();
            if ($res['yu'] < 0) {
                $res['payment'] = 2;
            }
            $res['material']        = $pa['material'];
            $res['agency_material'] = $pa['agency_material'];
            if ($pa) {
                $res['dep_money'] = $pa['money'];
                if ($pa['weixin'] == 2) {
                    $payment = db('recharge')->where(['order_no' => $res['order_no'], 'status' => 1, 'type' => 2, 'project' => $pa['payment_id']])->find();
                    if (!$payment && $res['yu'] > 0) {
                        if ($pa['pay_type'] == 0) {
                            $res['payment']      = 2;
                            $res['paymentTitle'] = '小程序未收';
                        } else {
                            $res['payment']      = 2;
                            $res['paymentTitle'] = '收款码支付';
                        }

                    }
                }
            }
            $da['ification'] = $res['ification'];
            $da['order_id']  = $res['order_id'];
            $kl[]            = $da;
            $capital         = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 0])->field('class_b,capital_id,revised,fen')->select();
            $agency          = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            if (!empty($res['cleared_time']) && empty($res['agency']) && !empty($capital)) {
                $res['settlement'] = 1;
            } elseif (!empty($res['cleared_time']) && !empty($res['agency']) && !empty($res['settlement_time']) && !empty($capital)) {
                $res['settlement'] = 1;
            } elseif (!empty($res['cleared_time']) && !empty($res['agency']) && empty($res['settlement_time']) && !empty($capital)) {
                $res['settlement'] = 0;
            } elseif (empty($res['cleared_time']) && !empty($res['agency']) && !empty($res['settlement_time']) && empty($capital)) {
                $res['settlement'] = 1;
            } else {
                $res['settlement'] = 0;
            }
            $fen = 1;
            if (!empty($capital)) {
                if ($capital[0]['fen'] == 4) {
                    $fen = 1;
                } else {
                    $fen = 0;
                }


            }
            $res['old'] = $fen;
            //判断
            if (!empty($capital) && !empty($agency) && empty($res['cleared_time']) && empty($res['settlement_time'])) {
                $res['agencyCount'] = 1;
            } elseif (!empty($capital) && empty($agency) && empty($res['cleared_time'])) {
                $res['agencyCount'] = 2;
            } elseif (!empty($capital) && !empty($res['cleared_time']) && !empty($agency) && empty($res['settlement_time'])) {
                $res['agencyCount'] = 3;
            } elseif (empty($capital) && !empty($agency) && empty($res['settlement_time'])) {
                $res['agencyCount'] = 3;
            } elseif (!empty($capital) && !empty($agency) && !empty($res['settlement_time']) && empty($res['cleared_time'])) {
                $res['agencyCount'] = 2;
            }
            if ($capital) {
                $res['revised'] = array_column($capital, 'revised')[0];
            } else {
                $res['revised'] = 0;
            }

            if (!empty($capital)) {
                $capital = array_column($capital, 'capital_id');
                $sql     = "SELECT SUM(`personal_price`) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`capital_id` in(" . implode(',', $capital) . ")";
                //原生sql
                $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital');
                $sum                = $reality_artificial->query($sql);
                if (isset($sum[0]['sum'])) {
                    $order_for_reality_artificial = round($sum[0]['sum'], 2);
                } else {
                    $order_for_reality_artificial = 0;
                }
            } else {
                $order_for_reality_artificial = 0;
            }
            $res['order_for_reality_artificial'] = $order_for_reality_artificial;//人工结算
            //预计利润
            $res['estimate'] = sprintf("%.2f", ($res['p'] - order_for_artificial($kl) - order_for_Finance($kl) - order_for_outlay($kl) - $res['agency']));
            //实际利润
            $res['actual'] = sprintf("%.2f", ($res['p'] - $order_for_reality_artificial - order_for_reality_material($kl) - order_for_outlay($kl) - $res['agency']));
            if (!empty($res['received_time']) && $res['state'] == 7) {
                $res['Tips'] = '结算后不能报销费用,及其它操作';
            } else {
                $res['Tips'] = '';
            }
            if (!empty($res['con_time'])) {
                $res['incDesSignature'] = db('capital')->where('ordesr_id', $data['order_id'])->where(function ($query) use ($res) {
                    $query->where(['types' => 2, 'untime' => ['>', strtotime($res['con_time'])]])->whereOr('increment=1  and crtime > ' . strtotime($res['con_time']));
                })->where('signed', 0)->count();
            }

            if ($res['weixin1'] == 9) {
                $res['type'] = 1;
            }
            $cc = $orderModel->ccSchemeLabel()->where('order_id', $res['order_id'])->select();
            if (!empty($cc)) {
                $schemeMasterCount = $schemeMaster->getList($res['order_id'], $this->us['user_id']);
                if ($schemeMasterCount == 0) {
                    $res['quickQuotation'] = 0;
                } else {
                    $res['quickQuotation'] = 1;
                }
            } else {
                $res['quickQuotation'] = 0;
            }
            $n      = '';
            $cclist = db('order_problem')->where('order_id', $res['order_id'])->select();

            $goods_category_id = array_merge(array_unique(array_column($cclist, 'goods_category_id')));
            foreach ($goods_category_id as $k => $item) {
                $daa['position'] = [];
                $daa['problem']  = [];
                foreach ($cclist as $value) {

                    if ($item == $value['goods_category_id']) {
                        $daa['title'] = $value['title'];
                        if ($value['type'] == 1) {
                            $daa['position'][] = [
                                "title" => $value['subhead'],

                            ];
                        } else {
                            $daa['problem'][] = [
                                "title" => $value['subhead'],
                            ];;

                        }
                    }

                }
                $n .= "\n" . "\n" . '问题:' . $daa['title'] . "\n" . '位置:' . implode(',', array_column($daa['position'], 'title')) . "\n" . '类型:' . implode(',', array_column($daa['problem'], 'title')) . "\n";
            }

            $res['remarks'] .= ';' . $n;
            db('through')->where('order_ids', $res['order_id'])->update(['handle' => time()]);
            \db('workbench_read')->where('order_id', $res['order_id'])->update(['have' => time(), 'already' => 0]);
            $labelList        = db('contact_label', config('database.zong'))->group('title')->where('status', 1)->count();
            $alreadyLabelList = db('order_contact_label', config('database.zong'))->where('telephone', $res['telephone'])->group('contact_name')->whereNull('delete_time')->select();

            $res['labelRate'] = '客户打标签  完成度' . sprintf('%.2f', count($alreadyLabelList) / $labelList * 100) . "％";
        } else {
            $res = null;
        }

        r_date($res);
    }

    /*
     * 待处理
     */
    public function PendingDisposal()
    {
        $data    = $this->model->post(['order_id']);
        $message = db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
        if ($message['already'] != 0) {
            db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
        }
        $res = db('remind')->where(['order_id' => $data['order_id'], 'admin_id' => $this->us['user_id']])->value('tai');
        if ($res != 0) {
            db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['tai' => 0]);
        }
        db('order')->where(['order_id' => $data['order_id']])->update(['undetermined' => 1, 'state' => 2, 'undetermined_time' => time()]);
        $orderSMS = json_decode(sendOrder($data['order_id']), true);
        (new PollingModel())->automatic($data['order_id'], 2);
        if ($orderSMS['code'] != 200) {
            r_date([], 300, '操作失败');
        }
        r_date([], 200);
    }

    /*
     * 沟通记录详情
     *
     */
    public function get_quote()
    {

        $data = $this->model->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id'] = $data['user_id'];
        }
        $res = db('order')->field('order.order_id,order.logo,order.order_no,order.addres,order.contacts,order.telephone,order.remarks,p.province,c.city,y.county,go.title')->join('goods_category go', 'order.pro_id=go.id', 'left')->join('user u', 'order.assignor=u.user_id ', 'left')->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->where(['order.order_id' => $data['order_id'], 'order.assignor' => $this->us['user_id']])->find();
        if ($res) {
            $res['logo']    = !empty($res['logo']) ? unserialize($res['logo']) : null;
            $res['remarks'] = !empty($res['remarks']) ? $res['remarks'] : '';
            if (!empty($data['through_id'])) {
                $res['gou'] = db('through')->where(['through_id' => $data['through_id']])->field('through_id,amount,remar,mode,th_time,log,end_time,capital_id')->order('th_time desc')->find();

            }
            if (!empty($res['gou'])) {
                $ca                                = db('envelopes')->where(['through_id' => $res['gou']['through_id']])->field('give_money,gong,give_b,wen_a,project_title,envelopes_id,expense,purchasing_expense,purchasing_discount')->find();
                $res['gou']['give_money']          = $ca['give_money'];
                $res['gou']['envelopes_id']        = $ca['envelopes_id'];
                $res['gou']['gong']                = $ca['gong'];
                $res['gou']['expense']             = $ca['expense'];
                $res['gou']['purchasing_discount'] = $ca['purchasing_discount'];
                $res['gou']['purchasing_expense']  = $ca['purchasing_expense'];
                $res['gou']['remar']               = !empty($res['gou']['remar']) ? $res['gou']['remar'] : null;
                $res['gou']['give_b']              = !empty($ca['give_b']) ? explode(',', $ca['give_b']) : null;
                $res['gou']['wen_a']               = !empty($ca['wen_a']) ? $ca['wen_a'] : '';
                $res['gou']['project_title']       = $ca['project_title'];
                if ($res['gou']['capital_id']) {
                    $allow               = db('allow')->where(['order_id' => $data['order_id'], 'capital_id' => $res['gou']['capital_id'], 'envelopes_id' => $ca['envelopes_id'], 'yc' => 2])->find();
                    $res['gou']['allow'] = $allow['id'];
                    $capital_id          = explode(',', $res['gou']['capital_id']);
                    foreach ($capital_id as $item) {
                        $res['gou']['company'][] = db('capital')->where(['capital_id' => $item, 'types' => 1])->field('class_a,class_b,company,square,un_Price,zhi,fen,capital_id,gold_suite as type,projectId,agency')->find();
                    }
                    foreach ($res['gou']['company'] as $k => $m) {
                        if ($m['fen'] == 0) {
                            $pro                                   = db('product_chan')->where(['product_id' => $m['projectId']])->field('product_id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['product_id'];
                        } elseif ($m['fen'] == 1) {
                            $pro                                   = db('detailed')->where(['detailed_id' => $m['projectId']])->field('detailed_id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['detailed_id'];
                        } else {
                            $pro                                   = db('information')->where(['class_b' => $m['class_b'], 'types' => 1, 'user_id' => $this->us['user_id'], 'un_Price' => $m['un_Price']])->field('id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['id'];
                        }
                        $res['gou']['company'][$k]['capital_id'] = $m['capital_id'];
                    }
                }
                $res['gou']['log']      = !empty($res['gou']['log']) ? unserialize($res['gou']['log']) : null;
                $res['gou']['th_time']  = !empty($res['gou']['th_time']) ? date("Y-m-d H:i", $res['gou']['th_time']) : '';
                $res['gou']['end_time'] = !empty($res['gou']['end_time']) ? date("Y-m-d H:i", $res['gou']['end_time']) : '';
                $res['gou']['amount']   = sprintf('%.2f', $res['gou']['amount'] + $ca['expense']);

            } else {
                $res['gou'] = null;
            }

        } else {
            $res = '';
        }
        r_date($res);
    }

    /**
     * 报价信息
     */
    public function get_jia()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->select();

        r_date($s, 200);
    }

    /**
     * 远程报价详情
     */
    public function get_yc()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->select();
        $da   = [0 => $s,];

        r_date($da, 200);
    }

    /**
     * 是否报价了
     */
    public function get_cha()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->find();
        if ($s) {
            r_date([], 300);
        } else {
            r_date([], 200);
        }

    }

    /*********************************************************************** * 重点标签***************************************************************************  */


    /**
     * 获取标签
     */
    public function get_label()
    {
        $res = db('label')->where(['user_id' => ['eq', 0]])->select();
        $rss = db('label')->where('user_id', $this->us['user_id'])->select();
        if ($rss) {
            $o = array_merge($res, $rss);
        } else {
            $o = $res;
        }

        r_date(array_values($o));
    }

    /**
     * 标记
     */
    public function point()
    {
        $data = $this->model->post(['type', 'order_id']);
        $b    = db('order')->where('order_id', $data['order_id'])->update(['point' => $data['type'], 'point_time' => time()]);
        r_date([], 200);
    }

    /*
     * 用户端显示报价
     */
    public function allow()
    {
        $data = $this->model->post(['order_id', 'envelopes_id', 'yc']);

        if ($data['yc'] == 1) {
            $yc = 2;
        } else {
            $yc = 1;
        }
        $allow = db('allow')->where(['order_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc])->find();

        if (empty($allow)) {
            $cop = \db('capital')->where(['ordesr_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id']])->column('capital_id');
            db('allow')->insertGetId(['order_id' => $data['order_id'], 'capital_id' => implode(',', $cop), 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc, 'time' => time(),]);
        }
        r_date([], 200);
    }

    /*
    * 用户端显示报价
    */
    public function all()
    {
        $data = $this->model->post(['envelopes_id', 'order_id', 'yc']);
        if ($data['yc'] == 0) {
            $yc = 1;
        } else {
            $yc = 2;
        }
        $allow = db('allow')->where(['order_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id']])->find();
        if (empty($allow)) {
            db('allow')->insertGetId(['order_id' => $data['order_id'], 'capital_id' => implode(',', db('capital')->where('envelopes_id', $data['envelopes_id'])->where('types', 1)->column('capital_id')), 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc, 'time' => time(),]);
        } else {
            db('allow')->where('id', $allow['id'])->update(['capital_id' => implode(',', db('capital')->where('envelopes_id', $data['envelopes_id'])->where('types', 1)->column('capital_id'))]);

        }
        r_date([], 200);
    }

    /*** ************************************************************确认时间***************************************************
     **************************************************************** types等于1是需要改变订单状态* types等于2是只需修改上门时间 */


    public function get_planned(PollingModel $pollingModel)
    {

        $data = $this->model->post(['order_id', 'planned', 'types', 'nodian']);
        db()->startTrans();
        try {
            $us = db('order')->where('order_id', $data['order_id'])->field('telephone,planned,undetermined,tui_jian,tui_role,pro_id')->find();
            if ($data['types'] == 1) {
                if ($us['undetermined'] == 1) {
                    orderModel::update(['undetermined' => 0], ['order_id' => $data['order_id']]);
                }
                db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['planned' => strtotime($data['planned']), 'state' => 2, 'update_time' => time(), 'appointment' => time()]);

                db('cc_task', config('database.cc'))->where('order_id', $data['order_id'])->where('type', 1)->where('status', 0)->update(['writetime' => strtotime($data['planned']), 'admin_id' => 0, 'status' => 1]);
                $user = $this->us['username'];
                if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                    sendMsg($us['telephone'], 8612, [$user, $data['planned']]);

                }
                if ($data['nodian'] != 1) {
                    remind($data['order_id'], 2);
                }
                $read = \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->find();
                if ($read) {
                    \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['have' => time(), 'already' => 0]);
                }
                \db('workbench_read')->insert(['type' => 1, 'order_id' => $data['order_id'], 'time' => strtotime($data['planned']), 'user_id' => $this->us['user_id']]);
                $y = ['planneds' => '', 'planned' => []];
            } elseif ($data['types'] == 2) {
                if ($us['undetermined'] == 1) {
                    orderModel::update(['undetermined' => 0], ['order_id' => $data['order_id']]);
                }
                db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['planned' => strtotime($data['planned']), 'update_time' => time(), 'appointment' => time()]);
                if (!empty($us['planned'])) {
                    db('planned')->insertGetId(['order_id' => $data['order_id'], 'planned' => $us['planned'],]);
                }
                $read = \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->find();
                if ($read) {
                    \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['have' => time(), 'already' => 0]);
                }
                \db('workbench_read')->insert(['type' => 1, 'order_id' => $data['order_id'], 'time' => strtotime($data['planned']), 'user_id' => $this->us['user_id']]);
                $y = ['planneds' => '', 'planned' => [],];

            } elseif ($data['types'] == 3) {
                $y = db('planned')->where(['order_id' => $data['order_id']])->field('planned')->order('id desc')->select();
                if (!empty($y)) {
                    foreach ($y as $k => $value) {
                        $y[$k] = !empty($value['planned']) ? date("Y-m-d H:i", $value['planned']) : '';
                    }
                    $y = ['planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '', 'planned' => !empty($y) ? $y : [],];
                } else {
                    $y = ['planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '', 'planned' => [],];
                }
            }
            if ($y) {
                db()->commit();
                json_decode(sendOrder($data['order_id']), true);

                r_date($y, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /*
     * 上门打卡
     */
    public function ClockIn(OrderModel $orderModel, \app\api\model\Common $common)
    {

        $data = $this->model->post(['order_id', 'lat', 'lng', 'picture', 'address']);

        $clock_in    = \db('clock_in')->where('order_id', $data['order_id'])->find();
        $punch_clock = time();
        $clock       = \db('clock_in')->insertGetId(['order_id' => $data['order_id'], 'lat' => $data['lat'], 'lng' => $data['lng'], 'address' => $data['address'], 'picture' => $data['picture'], 'punch_clock' => $punch_clock,]);
        if (empty($clock_in)) {
            $common->CommissionCalculation($data['order_id'], $orderModel, 1);
            $order = \db('order')->where('order_id', $data['order_id'])->value('state');
            if ($order < 4) {
                db('order')->where('order_id', $data['order_id'])->update(['state' => 3, 'undetermined' => 0]);
            }

            (new PollingModel())->Alls($data['order_id'], 2, 0, $punch_clock, $clock);
        }
        json_decode(sendOrder($data['order_id']), true);

        r_date(null, 200);
    }

    /**
     * 取消订单/退单子
     */
    public function get_reason(PollingModel $pollingModel)
    {
        $data = $this->model->post(['order_id', 'reason', 'tui_moey']);
        if (empty($data['tui_moey'])) {
            $state    = 8;
            $tui_time = time();
            if (empty($data['reason'])) {
                r_date([], 300);
            }
            $da = db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['state' => 8, 'reason' => $data['reason'], 'tui_time' => $tui_time, 'update_time' => $tui_time, 'port' => 3, 'undetermined' => 0]);
            (new PollingModel())->automatic($data['order_id'], time());
        } else {
            $state    = 9;
            $tui_time = time();
            if (empty($data['reason'])) {
                r_date([], 300);
            }
            if (empty($data['tui_moey'])) {
                r_date([], 300);
            }
            $da = db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['state' => 9, 'reason' => $data['reason'], 'tui_moey' => $data['tui_moey'], 'tui_state' => 1, 'tui_time' => $tui_time, 'update_time' => $tui_time, 'port' => 3]);
        }
//        $pollingModel->Alls($data['order_id'], $state, 0, time(), $tui_time);
        if ($da) {
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date('', 300, '编辑失败');
            }
            r_date([], 200);
        }
        r_date([], 300);
    }


    /*
     * 代购主材验收
     */
    public function CheckBefore()
    {
        $data = $this->model->post(['capital_id']);
        db()->startTrans();
        try {
            $prove = json_decode($data['prove'], true);
            if (empty($prove)) {
                throw new Exception('请填写凭证');
            }
            $id      = db('audit_materials')->insertGetId(['prove' => !empty($data['prove']) ? serialize($prove) : '', 'materials_remarks' => $data['materials_remarks'], 'capital_id' => $data['capital_id'], 'user_id' => $this->us['user_id'], 'creationtime' => time(), 'store_id' => $this->us['store_id'],]);
            $capital = db('capital')->where('capital_id', $data['capital_id'])->find();
            if ($capital['square'] != $data['square']) {
                db('capital')->where('capital_id', $data['capital_id'])->update(['square' => $data['square'], 'to_price' => $data['square'] * $capital['un_Price'], 'acceptance' => $id]);
                $where[] = ['exp', Db::raw("FIND_IN_SET(" . $data['capital_id'] . ",capital_id)")];
                $through = db('through')->where(['order_ids' => $capital['ordesr_id'], 'baocun' => 1])->where($where)->find();
                if ($through) {
                    $sum = db('capital')->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                    db('through')->where(['order_ids' => $capital['ordesr_id'], 'baocun' => 1])->update(['amount' => $sum]);
                }
            } else {
                db('capital')->where('capital_id', $data['capital_id'])->update(['acceptance' => $id]);
            }
            db()->commit();
            $oredr_count = db('capital')->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            $oredr       = db('capital')->where('acceptance', '<>', 0)->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            if ($oredr == $oredr_count) {
                db('order')->where(['order_id' => $capital['ordesr_id']])->update(['acceptance_time' => time()]);
            }
            json_decode(sendOrder($capital['ordesr_id']), true);
            r_date([], 200, '操作成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /*
     *
     * 开工设置
     */
    public function userlist()
    {
        $data = $this->model->post(['order_id']);
        $de   = db('startup')->where('orders_id', $data['order_id'])->field('sta_time,up_time,con,handover,xiu_id')->find();
        if ($de) {
            if (!empty($de['xiu_id'])) {
                $app_user = Db::connect(config('database.db2'))->table('app_user')->whereIn('app_user.id', $de['xiu_id'])->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_user.responsible,app_work_type.title')->select();
                $order_id = $data['order_id'];
                foreach ($app_user as $k => $value) {
                    $app_user[$k]['leader'] = Db::connect(config('database.db2'))->table('app_user_order')->where('order_id', $order_id)->where('user_id', $value['user_id'])->value('leader');
                    $work_tag               = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
                    $data                   = [];
                    foreach ($work_tag as $ks => $valu) {
                        switch ($ks) {
                            case 0:
                                $values = '漆工';
                                break;
                            case 1:
                                $values = '砖工';
                                break;
                            case 2:
                                $values = '抹灰工';
                                break;
                            case 3:
                                $values = '水电工';
                                break;
                            case 4:
                                $values = '室内防水工';
                                break;
                            case 5:
                                $values = '墙板安装工';
                                break;
                            case 6:
                                $values = '室内防水快修工';
                                break;
                            case 7:
                                $values = '高空作业防水工';
                                break;
                        }
                        if ($valu == 1) {
                            $data[] = $values;
                        }

                    }

                    $app_user[$k]['work_tag'] = implode(',', $data);
                    $app_user[$k]['check']    = false;
                }
                $de['shi'] = $app_user;
            } else {
                $de['shi'] = [];
            }
            $de['sta_time'] = !empty($de['sta_time']) ? date('Y-m-d H:i', $de['sta_time']) : '';
            $de['up_time']  = !empty($de['up_time']) ? date('Y-m-d H:i', $de['up_time']) : '';
            $de['handover'] = !empty($de['handover']) ? unserialize($de['handover']) : null;
        } else {
            $de = null;
        }

        r_date($de, 200);

    }

    /*
     * 获取师傅
     */
    public function get_master()
    {

        $data = \request()->post();

        $app_user = Db::connect(config('database.db2'))->table('app_user')->where('app_user.check', 1)->where('app_user.status', 1);
        if (isset($data['username']) && $data['username'] != '') {
            $app_user->whereLike('app_user.username', "%{$data['username']}%");
        }
        if (isset($data['store_id']) && $data['store_id'] != 0) {
            $app_user->where('app_user.store_id', $data['store_id']);
        }
        if (isset($data['work_type_id']) && $data['work_type_id'] != 0) {
            $app_user->where('app_user.work_type_id', $data['work_type_id']);
        }
        $user = $app_user->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_work_type.title')->select();

        foreach ($user as $k => $value) {
            $work_tag = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
            $data     = [];
            foreach ($work_tag as $ks => $valu) {
                switch ($ks) {
                    case 0:
                        $values = '漆工';
                        break;
                    case 1:
                        $values = '砖工';
                        break;
                    case 2:
                        $values = '抹灰工';
                        break;
                    case 3:
                        $values = '水电工';
                        break;
                    case 4:
                        $values = '室内防水工';
                        break;
                    case 5:
                        $values = '墙板安装工';
                        break;
                    case 6:
                        $values = '室内防水快修工';
                        break;
                    case 7:
                        $values = '高空作业防水工';
                        break;
                }
                if ($valu == 1) {
                    $data[] = $values;
                }

            }
            $user[$k]['work_tag'] = implode(',', $data);
            if ($value['store_id'] == $this->us['store_id']) {
                $user[$k]['color'] = 1;
            } else {
                $user[$k]['color'] = 0;
            }

        }
        $last_names = array_column($user, 'color');
        array_multisort($last_names, SORT_DESC, $user);
        r_date(['chen' => $user], 200);
    }

    /*
        *
        * 联系工程师
        */
    public function engineer()
    {
        $data    = $this->model->post(['order_id']);
        $results = send_post(UIP_SRC . "/support-v1/user/order-user", ['order_id' => $data['order_id']]);
        $results = json_decode($results);
        if ($results->code == 200) {
            $da['chen'] = $results->data;

            r_date($da, 200);
        } else {
            r_date([], 300, $results->msg);
        }

    }

    public function PaymentMethods()
    {
        $data = $this->model->post(['type']);
        //支付宝（重庆）https://images.yiniao.co/static/paycode/alipay_cq.jpg
        //微信（重庆）https://images.yiniao.co/static/paycode/wepay_cq.jpg
        if ($data['type'] == 3) {
            $url = 'https://images.yiniao.co/static/paycode/wepay_cd_wh_gy.jpg';
        } elseif ($data['type'] == 4) {
            $url = 'https://images.yiniao.co/static/paycode/alipay_cd_wh_gy.jpg';
        } elseif ($data['type'] == 7) {
            $url = 'https://images.yiniao.co/static/paycode/haoda_all.jpg';
        }
        r_date($url, 200);
    }

    /*
     * 开工设置
     */
    public function startup_settings()
    {

        $data = $this->model->post(['con', 'sta_time', 'up_time', 'order_id', 'shi_id', 'handover', 'leader']);
        if (!empty($data['up_time']) && !empty($data['sta_time'])) {
            if (strtotime($data['sta_time']) > strtotime($data['up_time'])) {
                r_date([], 300, "开工时间必须早于等于完工时间");
            }
        }
        db()->startTrans();
        try {
            $res = db('startup')->where(['orders_id' => $data['order_id']])->find();
            if ($res) {
                $o = ['con' => $data['con'],//备注
                    'sta_time' => strtotime($data['sta_time']), 'up_time' => strtotime($data['up_time']), 'xiu_id' => $data['shi_id'], 'handover' => !empty($data['handover']) ? serialize(json_decode($data['handover'], true)) : '',
                ];
                db('startup')->where('orders_id', $data['order_id'])->update($o);
            } else {
                $res = db('startup')->insertGetId(['con' => $data['con'],//备注
                    'sta_time' => strtotime($data['sta_time']), 'up_time' => strtotime($data['up_time']), 'orders_id' => $data['order_id'], 'xiu_id' => $data['shi_id'], 'handover' => !empty($data['handover']) ? serialize(json_decode($data['handover'], true)) : '',//图片,
                ]);

                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['startup_id' => $res]);
            }

            $us                    = db('order')->field('order.ification,order.telephone,co.con_time,co.contracType,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id,city.code')->join('contract co', 'order.order_id=co.orders_id', 'left')->join('city', 'order.city_id=city.city_id', 'left')->where('order_id', $data['order_id'])->find();
            $ca                    = db('envelopes')->where(['ordesr_id' => $data['order_id'], 'type' => 1])->field('give_money,gong')->find();
            $uss['order_id']       = $data['order_id'];
            $uss['remark']         = $data['con'];
            $uss['user_ids']       = $data['shi_id'];
            $uss['plan_start_at']  = strtotime($data['sta_time']);
            $uss['plan_end_at']    = strtotime($data['up_time']);
            $uss['plan_work_time'] = $ca['gong']; //师傅ID
            $uss['leader']         = $data['leader']; //师傅ID
            $uss['ascription']     = $this->us['store_id']; //师傅ID
            $uss['con_time']       = $us['con_time']; //师傅ID
            $uss['store_id']       = $this->us['store_id']; //师傅ID
            $result                = send_post(UIP_SRC . "/support-v1/order/add", $uss);
            $results               = json_decode($result, true);
            if ($results['code'] == 200) {
                $uscapital = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1])->field('wen_c')->select();
                if ($uscapital) {
                    if ($us['pro_id2'] != 129 && $uscapital[0]['wen_c'] != '暗埋水管打压检测') {
                        if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
//                            sendMsg($us['telephone'],15101,[$data['sta_time']]);
                        }

                    }
                }
                if ($us['contracType'] == 2) {
                    $ali  = new Aliyunoss();
                    $sign = \db('sign')->where('order_id', $data['order_id'])->find();
                    if (!empty($sign['contractpath']) && parse_url($sign['contractpath'])['host'] != 'imgaes.yiniaoweb.com' && parse_url($sign['contractpath'])['host'] != 'api.yiniaoweb.com') {
                        $contractpath = ROOT_PATH . 'public/' . substr(parse_url($sign['contractpath'])['path'], 4, 100);
                        if (file_exists($contractpath)) {
                            $oss_result = $ali->upload('contract/' . $us['code'] . '/' . $data['order_id'] . '.jpg', $contractpath);
                            if ($oss_result['info']['http_code'] == 200) {
                                $path = parse_url($oss_result['info']['url'])['path'];
                                db('sign')->where('order_id', $data['order_id'])->update(['contractpath' => 'https://images.yiniao.co' . $path]);
                                if (file_exists($contractpath)) {
                                    unlink($contractpath);
                                }

                            }
                        }

                    }
                    if (!empty($sign['agency_img']) && parse_url($sign['agency_img'])['host'] != 'imgaes.yiniaoweb.com' && parse_url($sign['agency_img'])['host'] != 'api.yiniaoweb.com') {
                        $agency_img = ROOT_PATH . 'public/' . substr(parse_url($sign['agency_img'])['path'], 4, 200);
                        if (file_exists($agency_img)) {
                            $oss_result = $ali->upload('contract/agency/' . $us['code'] . '/' . $data['order_id'] . 'd.jpg', $agency_img);
                            if ($oss_result['info']['http_code'] == 200) {
                                $paths = parse_url($oss_result['info']['url'])['path'];
                                \db('sign')->where('order_id', $data['order_id'])->update(['agency_img' => 'https://images.yiniao.co' . $paths]);
                                if (file_exists($agency_img)) {
                                    unlink($agency_img);
                                }
                            }
                        }

                    }

                }

                db()->commit();
                sendOrder($data['order_id']);
                r_date([], 200, '新增成功');
            } else {
                r_date([], 300, $results['msg']);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /**
     * 发起收款
     */
    public function payment(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $data = $this->model->post(['logos', 'weixin', 'orders_id', 'material', 'agency_material', 'uptime']);
        db()->startTrans();
        try {
            if ($data['weixin'] == 0) {
                throw new Exception('请选择付款方式');
            }
            $money = $data['material'] + $data['agency_material'];
            if ($money < 0) {
                throw new Exception('请走退款通道');
            }
            $lyu   = $orderModel->offer($data['orders_id'], 2);
            $money = $data['material'] + $data['agency_material'];
            if ($data['weixin'] != 2 && empty($data['logos'])) {
                throw new Exception('请上传图片');
            }
            $Common = $common::order_for_payment($data['orders_id']);
            if ($lyu['amount'] - $lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['amount'] - $lyu['agency'] - $Common[0]) < $data['material']) {
                    throw new Exception('主合同金额错误');
                }
            }
            if ($lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['agency'] - $Common[1]) < $data['agency_material']) {
                    throw new Exception('代购主材金额错误');
                }
            }
            if ($lyu['agency'] == 0 && $data['agency_material'] > 0) {
                $data['agency_material'] = 0;
            }
            if ($data['agency_material'] == 0 && $data['material'] == 0) {
                throw new Exception('金额错误');
            }
            $orderList = db('order')->join('user', 'order.assignor=user.user_id ', 'left')->where(['order.order_id' => $data['orders_id']])->field('user.store_id,order.state')->find();
            //有没有转派过
            $message = db('message')->where(['order_id' => $data['orders_id'], 'type' => 6])->order('id desc')->select();
            if (count($message) > 1) {
                $store_id = $orderList['store_id'];
            } else {
                $store_id = $this->us['store_id'];
            }
            $company_id               = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('company_id');
            $orderArray['company_id'] = $company_id;
            $orderState               = 0;
            //签约加金额审核
            if ($orderList['state'] == 3 && $data['weixin'] != 2) {
                $orderArray['company_id'] = $company_id;
                $orderArray['state']      = 4;
                $orderState               = 4;
                remind($data['orders_id'], 4);
                $common->CommissionCalculation($data['orders_id'], $orderModel);
            }
            db('order')->where(['order.order_id' => $data['orders_id']])->update($orderArray);
            db('payment')->insertGetId([
                'uptime' => strtotime($data['uptime']),//实际完工时间
                'logos' => !empty($data['logos']) ? serialize(json_decode($data['logos'], true)) : '',//图片
                'material' => $data['material'],
                'agency_material' => $data['agency_material'],
                'money' => $money,//合计
                'orders_id' => $data['orders_id'],
                'weixin' => $data['weixin'],
                'created_time' => time()
            ]);
            db()->commit();
            sendOrder($data['orders_id']);
            if ($orderState == 4) {
                $common->toExamine(2, $data['orders_id'], 1, '');
                $client = new Client();
                $client->index($data['orders_id'], $client::u8c_queue, $client::u8c_routingkey);
            }

            r_date([], 200, '新增成功');

        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /*
     * 通联获取收款二维码
     */

    public function GetQRcode(\app\api\model\PayModel $payModel, \app\api\model\Common $common)
    {
        $data            = $this->model->post(['weixin', 'orderId', 'material', 'agency_material']);
        $money           = $data['material'] + $data['agency_material'];
        $expiration_time = strtotime('+' . $payModel::validtime . 'minute');
        $payment         = db('payment')->insertGetId([
            'logos' => '',//图片
            'material' => $data['material'], 'agency_material' => $data['agency_material'], 'money' => $money,//合计
            'orders_id' => $data['orderId'], 'weixin' => $data['weixin'], 'created_time' => time(), 'pay_type' => 1, 'expiration_time' => $expiration_time,]);
        $received_time   = db('order')->join('goods_category go', 'order.pro_id=go.id', 'left')->where(['order.order_id' => $data['orderId']])->field('order.order_no,order.company_id,go.title')->find();

        $message = db('message')->where(['order_id' => $data['orderId'], 'type' => 6])->order('id desc')->select();
        if (count($message) > 1) {
            $store_id = db('order')->join('user', 'order.assignor=user.user_id ', 'left')->where(['order.order_id' => $data['orderId']])->value('user.store_id');
        } else {
            $store_id = $this->us['store_id'];
        }
        $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->find();

        if (!empty($received_time['company_id']) && $company_id['company_id'] == $received_time['company_id']) {

            $encryption = $common->encryption($received_time['company_id']);
        } else {

            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $this->us['store_id']])->where('status', 1)->find();

            $encryption[0] = $company_id['allpay_cusid'];
            $encryption[1] = $company_id['allpay_key'];
            $encryption[2] = $company_id['allpay_appid'];
            db('order')->where(['order.order_id' => $data['orderId']])->update(['company_id' => $company_id['company_id']]);
        }

        $s = $payModel->pay(['project' => $payment, 'money' => $money, 'order_no' => $received_time['order_no'], 'title' => $received_time['title'], 'cusid' => $encryption[0], 'key' => $encryption[1], 'APP_ID' => $encryption[2]]);
        r_date(['url' => $s, 'data' => '请在' . date('d', time()) . '日' . date('H点i分', $expiration_time) . '前完成支付', 'payment_id' => $payment, 'accountTips' => "支付时认准收款帐户为签约公司或成都益鸟科技有限公司"], 200);

    }

    /**
     * @param mixed 查询收款码
     */
    public function QueryCollectionCode()
    {
        $data     = $this->model->post(['order_id']);
        $request  = Request::instance();
        $pa       = db('payment')->where(['orders_id' => $data['order_id']])->order('payment_id desc')->field('weixin,pay_type,payment_id')->find();
        $recharge = 0;
        if ($pa['weixin'] == 2 && $pa['pay_type'] == 1) {
            $domain   = $request->domain();
            $recharge = db('recharge')->join('payment', 'payment.payment_id=recharge.project', 'left')->where(['payment.payment_id' => $pa['payment_id']])->where('payment.expiration_time', '>', time())->where('recharge.status', 0)->order('recharge.recharge_id desc')->field('recharge.order_nos,payment.money,payment.expiration_time,payment.payment_id')->find();
        }
        if (!empty($recharge)) {
            $AcceptData = ['url' => $domain . '/' . config('city') . '/qrcode/' . $recharge['order_nos'] . '.png', 'money' => $recharge['money'], 'data' => '请在' . date('d', time()) . '日' . date('H点i分', $recharge['expiration_time']) . '前完成支付', 'payment_id' => $recharge['payment_id'],];
        } else {
            $AcceptData = null;
        }

        r_date($AcceptData, 200);
    }

    /*
     * 剩余款项
     */
    public function surplus($order_id)
    {

        $list = (new OrderModel())->offer($order_id, 2);

        $Common         = \app\api\model\Common::order_for_payment($order_id);
        $da['material'] = 0;
        $da['amount']   = sprintf('%.2f', $list['amount'] - $list['agency']);
        if (!empty($list['amount'])) {
            $da['material'] = sprintf('%.2f', $list['amount'] - ($list['agency'] + $Common[0]));
        }
        if (!empty($Common[1]) || !empty($list['agency'])) {
            $da['agency_material'] = sprintf('%.2f', $list['agency'] - $Common[1]);
        } else {
            $da['agency_material'] = 0;
        }

        r_date($da, 200, '新增成功');
    }

    /*
     * 收款记录
     */
    public function CollectionRecord(Approval $approval)
    {
        $data = $this->model->post(['order_id']);

        $at = db('payment')->where('orders_id', $data['order_id'])->select();

        foreach ($at as $K => $item) {
            $at[$K]['cleared_time'] = empty($item['cleared_time']) ? '' : date('Y-m-d H:i', $item['cleared_time']);
            $at[$K]['logos']        = empty($item['logos']) ? null : unserialize($item['logos']);
            $at[$K]['state']        = empty($item['cleared_time']) ? 1 : 2;

            $at[$K]['uptime']          = empty($item['uptime']) ? '' : date('Y-m-d H:i', $item['uptime']);
            $at[$K]['expiration_time'] = empty($item['expiration_time']) ? '' : date('Y-m-d H:i', $item['expiration_time']);
            if ($item['weixin'] == 2 && $item['pay_type'] == 1) {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
                $at[$K]['weixin'] = $company[0]['title'];
            } else {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $item['weixin']));
                $at[$K]['weixin'] = $company[0]['title'];
            }
            if ($item['material'] == 0.00 && $item['agency_material'] == 0.00) {
                $material = $item['money'];
            } elseif ($item['material'] != 0.000) {
                $material = $item['material'];
            } else {
                $material = 0;
            }
            $at[$K]['material'] = $material;
            $at[$K]['type']     = $item['weixin'];

        }
        r_date($at, 200);
    }

    /*
 * 收款所有
 */
    public function CollectionRecordAll(Approval $approval)
    {

        $data = $this->model->post(['time', 'state', 'keywords']);
        $at   = db('payment')
            ->join('order', 'order.order_id=payment.orders_id', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left');
        if (isset($data['time']) && $data['time'] != '') {
            $start_time = strtotime(date('Y-m-d 0:0:0', strtotime($data['time'])));
            //当天结束之间
            $end_time = $start_time + 60 * 60 * 24;
            $at->whereBetween('payment.created_time', [$start_time, $end_time]);
        }
        if (isset($data['state']) && $data['state'] != 0) {
            if ($data['state'] == 1) {
                $at->whereNull('payment.cleared_time');
            } elseif ($data['state'] == 2) {
                $at->whereNotNull('payment.cleared_time');
            } else {

                $at->whereNotNull('payment.reject');
            }
        }
        if (isset($data['keywords']) && $data['keywords'] != '') {
            $at->where('order.addres|order.order_no', 'like', "%{$data['keywords']}%");
        }
        $at = $at->field('concat(p.province,c.city,y.county,order.addres) as addres,payment.payment_id,payment.reject,payment.success,order.order_no,payment.money,payment.weixin,payment.pay_type,(payment.material+payment.agency_material) as money,FROM_UNIXTIME(payment.created_time,"%Y年%m月%d日") as created_time,payment.cleared_time')
            ->where('order.assignor', $this->us['user_id'])
            ->order('payment.payment_id desc')
            ->select();


        foreach ($at as $K => $item) {
            if (!empty($item['cleared_time']) && empty($item['reject'])) {
                $at[$K]['cleared_time'] = "审核通过";
            } else if (empty($item['cleared_time']) && !empty($item['reject'])) {
                $at[$K]['cleared_time'] = "驳回";
            }
            if (($item['success'] == 1 || $item['success'] == 3) && $item['weixin'] == 2) {
                $at[$K]['success'] = "未支付";
            } else {
                $at[$K]['success'] = "已支付";
            }
            if ($item['weixin'] == 2 && $item['pay_type'] == 1) {

                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
                $at[$K]['weixin'] = $company[0]['title'];
            } else {

                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $item['weixin']));
                $at[$K]['weixin'] = $company[0]['title'];

            }


        }
        r_date($at, 200);
    }

    /*
 * 收款所有
 */
    public function CollectionRecordIndo(Approval $approval)
    {
        $data = $this->model->post(['payment_id']);

        $at = db('payment')
            ->join('order', 'order.order_id=payment.orders_id', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->field('concat(p.province,c.city,y.county,order.addres) as addres,go.title,order.order_no,order.order_id,payment.logos,payment.reject,payment.money,payment.weixin,payment.pay_type,payment.material,payment.agency_material,FROM_UNIXTIME(payment.created_time,"%Y年%m月%d日") as created_time,payment.success,payment.cleared_time')
            ->where('payment.payment_id', $data['payment_id'])
            ->find();

        if (!empty($at['cleared_time'])) {
            $at['cleared_time'] = date('Y-m-d H:i:s', $at['cleared_time']);
            $at['state']        = "审核通过";
            $at['cleared_name'] = "孙悦";
        } else {
            $at['cleared_time'] = "";
            $at['cleared_name'] = "孙悦";
        }

        if (!empty($at['reject'])) {
            $at['cleared_time'] = " ";
            $at['cleared_name'] = "孙悦";
            $at['state']        = "驳回";
        }
        if (($at['success'] == 1 || $at['success'] == 3) && $at['weixin'] == 2) {
            $at['success'] = "未支付";
        } else {
            $at['success'] = "已支付";
        }
        if ($at['weixin'] == 2 && $at['pay_type'] == 1) {
            $company      = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
            $at['weixin'] = $company[0]['title'];
        } else {
            $company      = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $at['weixin']));
            $at['weixin'] = $company[0]['title'];
        }
        $at['logos'] = empty($at['logos']) ? null : unserialize($at['logos']);
        if ($at['material'] == 0.00 && $at['agency_material'] == 0.00) {
            $material = $at['money'];
        } elseif ($at['material'] != 0.000) {
            $material = $at['material'];
        } else {
            $material = 0;
        }
        $at['material'] = $material;


        r_date($at, 200);
    }

    /*
    * 订单付款渠道
    */
    public function PaymentMethod($type = 1)
    {

        $payment_config = \db('payment_config', config('database.zong'))->where('status', 1)->where('city', config('cityId'))->find();
        if ($type == 1) {
            $get = Request::instance()->get();
            $paymentList = json_decode($payment_config['content'], true);
            if(isset($get['orderId'])){
                $channel_id = \db('order')->where('order_id', $get['orderId'])->value('channel_id');

                if ($channel_id == 11 || $channel_id == 40 || $channel_id == 41) {

                    $array=[];
                    foreach ($paymentList as $list) {
                        //淘宝
                        if($list['id']==5 && $channel_id == 11){
                            $array[]=$list;

                        }elseif ($list['id']==10 && $channel_id == 40){
                            //天猫
                            $array[]=$list;
                        }elseif ($list['id']==11 && $channel_id == 41){
                            $array[]=$list;
                        }
                    }
                    $paymentList=$array;

                }
            }

            r_date($paymentList, 200);
        } else {
            return $Data = json_decode($payment_config['compile'], true);
        }
    }

    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }

    public function unit()
    {
        $object = db('unit')->field('title,id')->select();

        r_date($object, 200);
    }

    /*
     * 支付是否成功轮询查询
     */
    public function CollectionInquiry(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $data       = $this->model->post(['payment_id']);
        $payment_id = db('payment')->where('payment_id', $data['payment_id'])->join('order', 'order.order_id=payment.orders_id', 'left')->field('payment.success,order.state,order.order_id')->find();
        if ($payment_id['success'] == 2) {
            if ($payment_id['state'] == 3) {
                db('order')->where('order_id', $payment_id['order_id'])->update(['state' => 4]);
                $state = db('order')->where('order_id', $payment_id['order_id'])->value('state');
                if ($state == 4) {
                    $common->CommissionCalculation($data['order_id'], $orderModel);
                    remind($payment_id['order_id'], 4);
                    $client = new Client();
                    $client->index($payment_id['order_id'], $client::u8c_queue, $client::u8c_routingkey);
                    sendOrder($payment_id['order_id']);
                    $common->toExamine(2, $payment_id['order_id'], 1, '');
                }

            }
            $sata = 1;
        } else {
            $sata = 2;
        }
        r_date(['success' => $sata], 200);
    }

    /**
     * 视频节点
     */
    public function jie()
    {

        $data    = $this->model->post(['order_ids']);
        $results = send_post(UIP_SRC . "/support-v1/node/list?order_id=" . $data['order_ids'], [], 2);
        $results = json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);
        } else {
            r_date([], 200, $results->msg);
        }

    }


    /*
    *
    * 订单发起返工
    */
    public function fan()
    {
        $data = $this->model->post();
        db()->startTrans();
        try {
            $order_rework = db('order_rework')->where(['rework_end' => $data['id']])->find();
            if (empty($order_rework)) {
                throw  new  Exception('信息不存在');
            }
            db('order')->where('order_id', $data['order_id'])->update(['rework' => 1]);
            db('order_rework')->where(['rework_end' => $data['id']])->update(['master_id' => $data['master_id'],]);

            db()->commit();
            sendOrder($data['order_id']);
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /*
    *
    * 订单发起返工获取师傅
    */
    public function MasterFanGong()
    {
        $data         = $this->model->post();
        $order_rework = db('order_rework')->where(['order_id' => $data['order_id'], 'rework_end' => $data['id']])->column('master_id');

        if (!empty($order_rework[0])) {

            $app_user = Db::connect(config('database.db2'))->table('app_user')->where('app_user.check', 1)->where('app_user.status', 1);
            $user     = $app_user->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_work_type.title')->whereIn('app_user.id', explode(',', $order_rework[0]))->select();
            foreach ($user as $k => $value) {
                $work_tag = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
                $data     = [];
                foreach ($work_tag as $ks => $valu) {
                    switch ($ks) {
                        case 0:
                            $values = '漆工';
                            break;
                        case 1:
                            $values = '砖工';
                            break;
                        case 2:
                            $values = '抹灰工';
                            break;
                        case 3:
                            $values = '水电工';
                            break;
                        case 4:
                            $values = '室内防水工';
                            break;
                        case 5:
                            $values = '墙板安装工';
                            break;
                        case 6:
                            $values = '室内防水快修工';
                            break;
                        case 7:
                            $values = '高空作业防水工';
                            break;
                    }
                    if ($valu == 1) {
                        $data[] = $values;
                    }

                }
                $user[$k]['work_tag'] = implode(',', $data);
                if ($value['store_id'] == $this->us['store_id']) {
                    $user[$k]['color'] = 1;
                } else {
                    $user[$k]['color'] = 0;
                }

            }
            $last_names = array_column($user, 'color');
            array_multisort($last_names, SORT_DESC, $user);
        }


        r_date(empty($user) ? null : $user, 200, '成功');

    }

    /*
    *
    * 获取返工原因状态
    */
    public function ReturnWorkReson()
    {
        $data             = $this->model->post();
        $re               = db('order_rework')->where(['order_id' => $data['order_id']])->field('reason')->find();
        $reason['reason'] = $re['reason'];
        r_date($reason, 200);

    }

    /*
     * 订单发起完工
     */
    public function ToBeFinished(PollingModel $pollingModel)
    {
        $data = $this->model->post(['order_id']);
        db()->startTrans();
        try {
            $envelopes_id          = db('envelopes')->where('type', 1)->where('ordesr_id', $data['order_id'])->value('envelopes_id');
            $capital               = db('capital')->where('envelopes_id', $envelopes_id)->where('types', 1)->column('capital_id');
            $auxiliary_interactive = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $data['order_id'])->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->count();

            $auxiliary_interactiveCount = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $data['order_id'])->where('auxiliary_delivery_node.state', 1)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->column('auxiliary_delivery_node.auxiliary_delivery_schedul_id');
            if ($auxiliary_interactive > count(array_merge(array_unique($auxiliary_interactiveCount)))) {
                throw  new  Exception('施工节点未上传，无法完工，请去工地巡检上传节点');
            }
            $result             = send_post(UIP_SRC . "/support-v1/order/all-finish", ['order_id' => $data['order_id']]);
            $results            = json_decode($result, true);
            $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order')->where('status', '<>', 10)->where(['order_id' => $data['order_id']])->whereNull('deleted_at')->select();
            $time               = [];
            if ($results['code'] == 200) {
                if ($reality_artificial) {
                    foreach ($reality_artificial as $value) {
                        $time[] = $value['finish_at'];
                        if ($value['start_at'] != 0) {
                            $times[] = $value['start_at'];
                        }
                    }
                    if (count($reality_artificial) == count($time)) {
                        $max_time    = array_search(max($time), $time);
                        $finish_time = $time[$max_time];
                        Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->update(['all_finish_at' => $finish_time]);
                    }
                    if (isset($times) && is_array($times)) {
                        $max_times  = array_search(min($times), $times);
                        $start_time = $times[$max_times];

                    } else {
                        $start_time = time();
                    }
                    OrderModel::update(['state' => 7, 'finish_time' => $time[$max_time], 'start_time' => $start_time], ['order_id' => $data['order_id']]);
                } else {
                    OrderModel::update(['state' => 7, 'finish_time' => time(), 'start_time' => time()], ['order_id' => $data['order_id']]);
                }
                $pollingModel->Alls($data['order_id'], 4, 0, time());

            }
            db()->commit();
            json_decode(sendOrder($data['order_id']), true);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /*
     * 返回状态返回施工中
     */
    public function Unsettled($order_id)
    {
        $order = db('order')->where('order_id', $order_id)->find();
        if (empty($order['cleared_time']) && empty($order['settlement_time'])) {
            OrderModel::update(['state' => 4, 'finish_time' => '',], ['order_id' => $order_id]);
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $order_id, 'status' => 4])->update(['status' => 3]);
            $client = new Client();
            $client->index($order_id, $client::u8c_queue, $client::u8c_routingkey);
            json_decode(sendOrder($order_id), true);
            r_date([], 200);
        }
        r_date([], 300, '该订单已结算不能返回施工中');


    }

    /*
    *结算标记
    */
    public function SettlementMark($order_id, $type)
    {

        $main_payment  = 0;
        $main_payment1 = 0;
        $agent_payment = 0;
        $re            = db('order')->field('concat(p.province,c.city,y.county,order.addres) as  addres,order.cleared_time,order.settlement_time')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where('order_id', $order_id)
            ->find();
        $io            = db('payment')->where('orders_id', $order_id)->where('cleared_time', '>', 0)->field('money,weixin,success,material,agency_material,uptime')->select();
        foreach ($io as $value) {
            if ($value['weixin'] != 2 && $value['success'] == 1) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment  += $value['money'];
                    $main_payment1 += $value['money'];
                }
                if ($value['material'] != 0 && $value['uptime'] > 1625068800) {
                    $main_payment += $value['material'];
                }
                if ($value['material'] != 0) {
                    $main_payment1 += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment += $value['agency_material'];
                }
            }
            if ($value['weixin'] == 2 && $value['success'] == 2) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment  += $value['money'];
                    $main_payment1 += $value['money'];
                }
                if ($value['material'] != 0 && $value['uptime'] > 1625068800) {
                    $main_payment += $value['material'];
                }
                if ($value['material'] != 0) {
                    $main_payment1 += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment += $value['agency_material'];
                }
            }

        }
        $money = OrderModel::offer($order_id);
        if ($type == 1 && round(((string)$money['amount'] - (string)$agent_payment), 2) == round((string)$main_payment1, 2)) {
            if (!empty($re['cleared_time'])) {
                r_date(null, 300, '该订单已经结算');
            }
            $purchase_usage = db('purchase_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
            $routine_usage  = db('routine_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
            if (!empty($purchase_usage) || !empty($routine_usage)) {

                r_date(null, 300, '有直达工地的材料申请正在审核中');
            }
            $_reimbursement = db('reimbursement')->where('classification', '<>', 4)->where(['order_id' => $order_id])->where(function ($query) {
                $query->whereOr('status', 0)->whereOr('status', 3);
            })->count();
            if ($_reimbursement != 0) {
                r_date([], 300, '你有费用报销未通过');
            }
            $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $order_id)->whereNull('deleted_at')->sum('personal_price');

            $orderCapital = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $order_id)->where('status', 1)->sum('money');
            if ($personal_price < $orderCapital) {
                r_date([], 300, '不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
            }

            $material_usage = db('material_usage')->where(['status' => 0, 'order_id' => $order_id])->count();
            if ($material_usage != 0) {
                r_date([], 300, '你有材料未通过');
            }
            if ((string)$money['amount'] != (string)sprintf('%.2f', ($agent_payment + $main_payment1))) {
                r_date([], 300, '请联系管理员');
            }
            $reimbursement  = 0;
            $material_usage = db('material_usage')->where(['status' => 1, 'order_id' => $order_id])->where('adopt', '>', '1625162399')->sum('total_price');
            $_reimbursement = db('reimbursement')->where(['order_id' => $order_id])->where('adopt', '>', '1625068800')->where('classification', '<>', 4)->where('status', 1)->select();
            $Break          = 0;
            $Small          = 0;
            $people         = 0;
            $freight        = 0;
            foreach ($_reimbursement as $i) {
                if ($i['classification'] == 1) {
                    //建渣打拆
                    $Break += $i['money'];
                } elseif ($i['classification'] == 2) {
                    //小材料
                    $Small += $i['money'];
                } elseif ($i['classification'] == 3) {
                    //协作人工
                    $people += $i['money'];
                } elseif ($i['classification'] == 7) {
                    //运费
                    $freight += $i['money'];
                }
                $reimbursement += $i['money'];
            }
            if ($main_payment != 0) {
                U8cMasters('收到' . $re['addres'] . '主合同销售收款结算', $main_payment, $order_id, 15);
            }


            $sql = "SELECT (SUM(`personal_price`)-SUM(`half_price`)) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`order_id` =" . $order_id;


            $largeReimbursement = db('large_reimbursement')->where(['order_id' => $order_id])->sum('money');
            //原生sql
            $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital');
            $sum                = $reality_artificial->query($sql);
            if (isset($sum[0]['sum'])) {
                $order_for_reality_artificial = round($sum[0]['sum'], 2) - $largeReimbursement;
            } else {
                $order_for_reality_artificial = 0;
            }

            if ($order_for_reality_artificial != 0) {
                U8cMasters('收到' . $re['addres'] . '师傅提成结算', $order_for_reality_artificial, $order_id, 11);
            }


            $aggregate = [];
            if (!empty($Break)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '建渣打拆结算',
                    'money' => round($Break, 2),
                    'orderId' => $order_id,
                    'type' => 18,
                ]);
            }
            if (!empty($Small)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '小材料结算',
                    'money' => round($Small, 2),
                    'orderId' => $order_id,
                    'type' => 19,
                ]);
            }
            if (!empty($people)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '协作人工结算',
                    'money' => round($people, 2),
                    'orderId' => $order_id,
                    'type' => 17,
                ]);
            }
            if (!empty($largeReimbursement)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '师傅提成',
                    'money' => round($largeReimbursement, 2),
                    'orderId' => $order_id,
                    'type' => 22,
                ]);
            }
            if (!empty($freight)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '运费结算',
                    'money' => round($freight, 2),
                    'orderId' => $order_id,
                    'type' => 20,
                ]);
            }

            if (!empty($material_usage)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '材料成本结算',
                    'money' => round($material_usage, 2),
                    'orderId' => $order_id,
                    'type' => 16,
                ]);
            }

            if (!empty($aggregate)) {
                U8cBatch($aggregate);
            }
            OrderModel::update(['cleared_time' => time()], ['order_id' => $order_id]);
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $order_id])->update(['cleared_time' => time()]);

            $orderSMS = json_decode(sendOrder($order_id), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            $client = new Client();
            $client->index($order_id, $client::u8c_queue, $client::u8c_routingkey);
            $Common     = new Common();
            $orderModel = new OrderModel();
            $Common->award_config_rule($order_id, $orderModel, 3);
            r_date([], 200, '成功');
        }

        if ($type == 2 && round(((string)$money['amount'] - (string)$main_payment1), 2) == round((string)$agent_payment, 2)) {
            if (!empty($re['settlement_time'])) {
                r_date(null, 300, '该订单已经结算');
            }
            $_reimbursement      = db('reimbursement')->where(['order_id' => $order_id])->where('classification', 4)->where(function ($query) {
                $query->whereOr('status', 0)->whereOr('status', 3);
            })->count();
            $reimbursementMoney1 = db('reimbursement')->where(['order_id' => $order_id])->where('classification', 4)->field('status,money')->select();
            $money1              = [];
            foreach ($reimbursementMoney1 as $list) {
                if ($list['status'] == 1) {
                    $money1[] = $list['money'];
                }

            }
            if (count($reimbursementMoney1) == 0) {
                r_date([], 300, '没有主材请款，不能结算');
            }
            if ($_reimbursement != 0) {
                r_date([], 300, '你有费用报销未通过');
            }
            $order = db('order')->where(['order_id' => $order_id])->field('acceptance_time')->find();
            if (empty($order['acceptance_time'])) {
                r_date([], 300, '请验收后结算');
            }
            if ((string)$money['amount'] != (string)($agent_payment + $main_payment1)) {
                r_date([], 300, '请联系管理员');
            }
            if ($agent_payment != 0) {
                U8cMasters('收到' . $re['addres'] . '代购合同销售收款结算', round($agent_payment, 2), $order_id, 14);
            }
            if (array_sum($money1) != 0) {
                U8cMasters('收到' . $re['addres'] . '代购请款结算', round(array_sum($money1), 2), $order_id, 12);
            }
            OrderModel::update(['settlement_time' => time()], ['order_id' => $order_id]);
            $orderSMS = json_decode(sendOrder($order_id), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            $client = new Client();
            $client->index($order_id, $client::u8c_queue, $client::u8c_routingkey);
            r_date([], 200, '成功');
        }
        r_date([], 300, '收款审核中');


    }


    /*
     * 师傅结算50%
     */
    public function HalfSettlement()
    {

        r_date([], 300, '已停止此功能');

//        Db::connect(config('database.db2'))->startTrans();
//        OrderModel::startTrans();
//        try {
//            OrderModel::update(['master_half_cost_time'=>time()], ['order_id'=>$data['order_id']]);
//            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$data['order_id']])->update(['master_half_cost_time'=>time()]);
//            Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $data['order_id'])->where('deleted_at', 'null')->update(['half_price'=>Db::raw('personal_price*0.5')]);
//            Db::connect(config('database.db2'))->commit();
//            OrderModel::commit();
//            r_date([], 200);
//        } catch (Exception $e) {
//            Db::connect(config('database.db2'))->rollback();
//            OrderModel::rollback();
//            r_date([], 300, $e->getMessage());
//        }
    }


    public function SettlementMarks($order_id, $type)
    {
        $main_payment  = 0;
        $main_payment1 = 0;
        $agent_payment = 0;
        $re            = db('order')->field('concat(p.province,c.city,y.county,order.addres) as  addres')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where('order_id', $order_id)
            ->find();
        $io            = db('payment')->where('orders_id', $order_id)->where('cleared_time', '>', 0)->field('money,weixin,success,material,agency_material,uptime')->select();
        foreach ($io as $value) {
            if ($value['weixin'] != 2 && $value['success'] == 1) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment  += $value['money'];
                    $main_payment1 += $value['money'];
                }
                if ($value['material'] != 0 && $value['uptime'] > 1625068800) {
                    $main_payment += $value['material'];
                }
                if ($value['material'] != 0) {
                    $main_payment1 += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment += $value['agency_material'];
                }
            }
            if ($value['weixin'] == 2 && $value['success'] == 2) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment  += $value['money'];
                    $main_payment1 += $value['money'];
                }
                if ($value['material'] != 0 && $value['uptime'] > 1625068800) {
                    $main_payment += $value['material'];
                }
                if ($value['material'] != 0) {
                    $main_payment1 += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment += $value['agency_material'];
                }
            }

        }
        $money = OrderModel::offer($order_id);
        if ($type == 1 && round(((string)$money['amount'] - (string)$agent_payment), 2) == round((string)$main_payment1, 2)) {
            $purchase_usage = db('purchase_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
            $routine_usage  = db('routine_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
            if (!empty($purchase_usage) || !empty($routine_usage)) {

                r_date(null, 300, '有直达工地的材料申请正在审核中');
            }
            $_reimbursement = db('reimbursement')->where('classification', '<>', 4)->where(['order_id' => $order_id])->where(function ($query) {
                $query->whereOr('status', 0)->whereOr('status', 3);
            })->count();
            if ($_reimbursement != 0) {
                r_date([], 300, '你有费用报销未通过');
            }
            $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $order_id)->whereNull('deleted_at')->sum('personal_price');

            $orderCapital = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $order_id)->where('status', 1)->sum('money');
            if ($personal_price < $orderCapital) {
                r_date([], 300, '不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
            }

            $material_usage = db('material_usage')->where(['status' => 0, 'order_id' => $order_id])->count();
            if ($material_usage != 0) {
                r_date([], 300, '你有材料未通过');
            }

            if ((string)$money['amount'] != (string)sprintf('%.2f', ($agent_payment + $main_payment1))) {
                r_date([], 300, '请联系管理员');
            }

            $reimbursement  = 0;
            $material_usage = db('material_usage')->where(['status' => 1, 'order_id' => $order_id])->where('adopt', '>', '1625162399')->sum('total_price');
            $_reimbursement = db('reimbursement')->where(['order_id' => $order_id])->where('adopt', '>', '1625068800')->where('classification', '<>', 4)->where('status', 1)->select();
            $Break          = 0;
            $Small          = 0;
            $people         = 0;
            $freight        = 0;
            foreach ($_reimbursement as $i) {
                if ($i['classification'] == 1) {
                    //建渣打拆
                    $Break += $i['money'];
                } elseif ($i['classification'] == 2) {
                    //小材料
                    $Small += $i['money'];
                } elseif ($i['classification'] == 3) {
                    //协作人工
                    $people += $i['money'];
                } elseif ($i['classification'] == 7) {
                    //运费
                    $freight += $i['money'];
                }
                $reimbursement += $i['money'];
            }
            if ($main_payment != 0) {
                U8cMasters('收到' . $re['addres'] . '主合同销售收款结算', $main_payment, $order_id, 15);
            }


            $sql = "SELECT (SUM(`personal_price`)-SUM(`half_price`)) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`order_id` =" . $order_id;


            $largeReimbursement = db('large_reimbursement')->where(['order_id' => $order_id])->sum('money');
            //原生sql
            $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital');
            $sum                = $reality_artificial->query($sql);
            if (isset($sum[0]['sum'])) {
                $order_for_reality_artificial = round($sum[0]['sum'], 2) - $largeReimbursement;
            } else {
                $order_for_reality_artificial = 0;
            }

            if ($order_for_reality_artificial != 0) {
                U8cMasters('收到' . $re['addres'] . '师傅提成结算', $order_for_reality_artificial, $order_id, 11);
            }


            $aggregate = [];
            if (!empty($Break)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '建渣打拆结算',
                    'money' => round($Break, 2),
                    'orderId' => $order_id,
                    'type' => 18,
                ]);
            }
            if (!empty($Small)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '小材料结算',
                    'money' => round($Small, 2),
                    'orderId' => $order_id,
                    'type' => 19,
                ]);
            }
            if (!empty($people)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '协作人工结算',
                    'money' => round($people, 2),
                    'orderId' => $order_id,
                    'type' => 17,
                ]);
            }
            if (!empty($largeReimbursement)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '师傅提成',
                    'money' => round($largeReimbursement, 2),
                    'orderId' => $order_id,
                    'type' => 22,
                ]);
            }
            if (!empty($freight)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '运费结算',
                    'money' => round($freight, 2),
                    'orderId' => $order_id,
                    'type' => 20,
                ]);
            }

            if (!empty($material_usage)) {
                array_push($aggregate, [
                    'explanation' => '收到' . $re['addres'] . '材料成本结算',
                    'money' => round($material_usage, 2),
                    'orderId' => $order_id,
                    'type' => 16,
                ]);
            }

            if (!empty($aggregate)) {
                U8cBatch($aggregate);
            }
            OrderModel::update(['cleared_time' => time()], ['order_id' => $order_id]);
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $order_id])->update(['cleared_time' => time()]);

            $orderSMS = json_decode(sendOrder($order_id), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            $client = new Client();
            $client->index($order_id, $client::u8c_queue, $client::u8c_routingkey);
            r_date([], 200, '成功');
        }
    }

}